JavaScript 继承(原型链,对象冒充)

一、对象冒充

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
   
</head>
<body>
    <script>
        function Person(name, age) {
            this.name = name;
            this.age = age;
            this.show = function () {
                document.getElementById("target1").innerHTML = "name:" + this.name + "<br>age:" + this.age+"<br>";
            }
        }

        var p = new Person("小学森", 12);
        p.show();
        function Student(name, age, score) {
        
           // this.newMethod = Person;
            //this.newMethod(name, age);
            //delete newMethod;

            this.score = score;
            this.show = function () {
                document.getElementById("target2").innerHTML = "name:" + this.name + "<br>age:" + this.age + "<br>score:" + this.score + "<br>";
            }
        }

        var stu = new Student("小学森", 12, 100);
        stu.show();
    </script>
</body>
</html>

二、call() 与 apply()

1.call()
将以上代码注释部分替换为:

    Person.call(this, name, age);

call()方法的第一个参数用作this的对象,其他参数与函数对应
2.apply()
将以上代码注释部分替换为

 Person.apply(this, new Array(name, age));

第一个参数为this,第二个参数为要传递给函数的参数数组。

三、原型链

function ClassA() {

        }

        ClassA.prototype.color = "red";
        ClassA.prototype.sayColor = function () {
            alert(this.color);
        }

        function ClassB() {

        }

        ClassB.prototype = new ClassA();

        ClassB.prototype.name = "";
        ClassB.prototype.sayName = function () {
            alert(this.name);
        }


        var objA = new ClassA();
        var objB = new ClassB();
        objA.color = "yellow";
        objB.color = "blue";
        objB.name = "xx";
        objA.sayColor();
        objB.sayColor();
        objB.sayName();

四、混合方式

function ClassA(sColor) {
            this.color = sColor;
        }

        ClassA.prototype.sayColor = function () {
            alert(this.color);
        }

        function ClassB(sColor, sName) {
            ClassA.call(this, sColor);
            this.name = sName;
        }

        ClassB.prototype = new ClassA();

        ClassB.prototype.sayName = function () {
            alert(this.name);
        }

        var objA = new ClassA("red");
        var objB = new ClassB("yellow", "admin");
        objA.sayColor();
        objB.sayColor();
        objB.sayName();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值