JavaScript使用伪造方式实现继承

<script>
    function Parent(name, age) {
        this.color = ["red", "blue"];
        this.name = name;
        this.say = function () {
            alert(this.name + ',' + this.age);
        }
    }
    Parent();

    /**
     * 使用伪造的方式就可以把子类的构造函数参数传递到父类中,
     *上面的方法say继承了下来,但是每个对象都一个say方法,占用内存过大。
     * 需要使用组合的方式来解决。
     */
    function Child(name, age) {
        this.age = age;
        // 在Child中的this明显应该是指向Child的对象
        // 当调用Parent方法的时候,而且this又是指向了Child
        // 此时就等于在这里完成了this.color = ['red','blue']
        // 也就等于在Child中有了this.color属性,这样也就变相的完成了继承
        Parent.call(this, name);
        // 这种调用方式,Parent的上下文是window对象,根本无法实现继承
        // Parent();
    }
    var c1 = new Child("jack", 35);
    c1.color.push("green");
    //    alert(c1.color);
    //   alert(c1.name);
    //   alert(c1.age);
    c1.say();

    var c2 = new Child("Ann", 23);
    c2.color.push("black");
    //   alert(c2.color);
    //    alert(c2.name);
    //    alert(c2.age);
    c2.say();
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值