今天再次看js继承,有了新的理解。其实是对作用域的进一步理解
首先看一个例子:
function A(name){
this.name = name;
this.sayHello = function(){alert(this.name+” say Hello!”);};
}
function B(name,id){
this.temp = A;
this.temp(name); //相当于new A();
delete this.temp; //防止在以后通过temp引用覆盖超类A的属性和方法
this.id = id;
this.checkId = function(ID){alert(this.id==ID)};
}
这是经典的对象冒充,标红的那两行相当于执行了A(name),并且执行后A中的this已经换成了B中的this。
那么我们把标红的部分直接换成 A(name)会怎样呢?
如此我们做试验
var b = new B("B","BID");
alert(b.name);//undefined
为何?
因为执行A的时候没有绑定作用域,this仍然是window
我们输出alert(window.name)或alert(name)//B
那么这中对象冒充实际上就是变换了this,绑定作用域到某个对象上
那么除了这个方法还有没有其他方法呢?
apply和call
个人理解的作用:调用函数并绑定作用域
这就是对象冒充的含义