JavaScript使用伪造方式实现继承

来源:互联网 发布:ubuntu wine qq 乱码 编辑:程序博客网 时间:2024/05/29 02:17
<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
原创粉丝点击