js的对象冒充

function Parent(name)
{
    this.name = name;
    this.sayHello = function()
    {
        alert(this.name)
    }
}

function Child(name, age)
{
    //用子类的this去冒充父类的this,实现继承
    this.method = Parent;
    this.method(name);
    delete this.method;
    
    //此后的this均指子类
    this.age = age;
    this.sayWorld = function()
    {
        alert(age);
    }
}
var parent = new Parent("张三");
var child = new Child("李四", 20);

例子中为什么要把Parent赋给Child的临时属性this.method再运行,直接不赋给this.method,直接运行method(name)不行吗?求教

阅读 1.9k
3 个回答

直接运行还叫继承吗? 那就是调用啊

//用子类的this去冒充父类的this,实现继承

这注释已经写得很清楚了...

这么做是为了保障method中的this指向child,直接运行method,method中的this指向window。可以改用apply或call,效果一样

Parent.call(this, name)
推荐问题