//对象冒充
function FuncA(){
    this.name = 'A';
}function FuncB(){
    this.method = FuncA;
    this.method();//不就等同于FuncA()么;
    delete this.method;
}
var a = new FuncA();
var b = new FuncB();
/*
alert(typeof a);
alert(typeof b);
alert(typeof FuncA);
alert(typeof FuncB);
*/
alert(b.name);this.method()之中究竟做了哪些操作呢?

解决方案 »

  1.   

    要理解这个就要先搞清楚this
    换个例子//对象冒充
    function FuncA(){
        this.name = 'A';
        this.age=30;
    }
     
    function FuncB(){
        this.method = FuncA;
        this.method();//不就等同于FuncA()么;
        delete this.method;
        this.color ="red";
    }
    var a = new FuncA();
    var b = new FuncB();
    console.log(a.name);
    console.log(b.name);console.log(a.color);
    console.log(b.color);
    this.method();就是执行了A的构造函数,然后再删除,可以接着执行本身的构造函数,从而完成继承模拟。
      

  2.   

    给实例添加了一个name属性,并且设置name的值为A
      

  3.   

    其实最重要的是this.method = FuncA;这句。
      

  4.   

    this.method();//不就等同于FuncA()么;
    错,是等同于FuncA.call(this);
    直接执行FuncA里面的this因为作用域关系与外面的this指向不一致,将无法把name成员添加到当前对象,而会添加到window对象上去
    其实可以写得更简单:
    function FuncB(){
        FuncA.call(this);
    }
    你这点代码只是完成构造函数成员的继承,还要继承原型链上的成员才算圆满
      

  5.   


    你的意思就是  就跟嵌套function一样。里面的this跟外层的this不同,必须用一个变量保存外层的this,在传入给内层嵌套的函数使用是吧。
      

  6.   

    和你说的情况不同,这儿不是函数嵌套,不过原理差不多。call方法是Function类的成员,可以指定一个对象调用函数(即指定this),在组件编写中通常用于写回调函数时指定调用者,也适合用于继承