js的函数非常常见,当一个函数被当成构造函数来用时,其中的this会指向该构造函数的实例,但是有时候可能会不小心直接执行该方法,这时候this会绑定到全局对象window上(非严格模式),下面上代码说明:
function Parent(){
this.name='kasol';
this.age=25;
this.getName=function(){
return this.name;
}
}
var parent=new Parent();
parent.name //kasol
这时候如果直接调用Parent的话
Parent();
window.name //kasol
这显然不是我们想要的,这时候我们可以稍微改造一下Parent函数
function Parent(){
if(this instanceof Parent){
this.name='kasol';
this.age=25;
this.getName=function(){
return this.name;
}
}else {
return new Parent();
}
}
这样一来就不用担心了,但是有时候我们在借用构造函数继承属性时,这又会导致属性继承遭到破坏:
function Child(){
Parent.call(this);
this.weight=68;
this.height=175;
}
var child=new Child();
child.name //undefind
这里在new一个Child实例时,调用父类构造函数,由于此时this不是Parent的实例,所以会返回一个新的Parent对象,之后也没有其他操作,所以child的name属性不存在。所以此时需要加上原型链:
function Child(){
Parent.call(this);
this.weight=68;
this.height=175;
}
Child.prototype=new Parent();
var child=new Child();
child.name //kasol
此时child实例就会有name属性了