function Fun() {
this.name = "mary";
this.sec = function () {
console.log("sec");
}
}
function CopyFun() {
// Fun.call(this);
this.fun = Fun;
this.fun();
}
var fun = new CopyFun();
fun.sec(); // sec
console.log(fun.name); // mary
console.log(fun.hasOwnProperty("sec")); // true
为什么CopyFun中this.fun()方法执行就可以创建属性?
我是这样理解的:
this.fun = function(){
this.name = "mary";
this.sec = function () {
console.log("sec");
}
}
当执行 this.fun()
这一步时应该是一个正常函数的调用,由于没有返回值所以应该返回undefined。
但实际情况是,它相当于执行了Fun.call(this)
,创建的属性name和sec,这一点不能理解,望哪位大神给解释一下,谢谢!!!。
其实你加个console.log看看this就知道了。
this.fun()
的确没有返回值(怎么理解这个正常函数调用呢?这里我认为是在调用实例的fun方法了,所以fun方法里面的this指向的是实例),但它执行体里 this指向的就是CopyFun的实例,那么this.name
等就是在给实例赋值成员了。