【发布时间】:2015-11-02 03:28:54
【问题描述】:
一个关于javascript原型的奇怪问题:
(function(w){
if(!w)
return;
var TestJS = function(){
};
TestJS.prototype = {
data:{},
initData:function(){
this.data={
val_name_1 : 1,
val_name_2 : 2,
val_name_3 : "hello-3"
};
console.log(this.data);
return this;
},
TestChildJS:{
initChild:function(){
console.log(TestJS);
console.log(TestJS.data);
console.log(new TestJS().data.val_name_1);
console.log(TestJS.data.val_name_1);
}
}
};
window.TestJS = new TestJS();
})(window);
为什么'TestChildJS'不能得到'val_name_1'?
TestJS.initData();
console.log(TestJS.TestChildJS.initChild());
所以我必须这样写我的代码:
(function(w){
if(!w)
return;
var TestJS = function(){
};
TestJS.prototype = {
data:{},
initData:function(){
this.data={
val_name_1 : 1,
val_name_2 : 2,
val_name_3 : "hello-3"
};
console.log(this.data);
this.TestChildJS.initParentData(this);
return this;
},
TestChildJS:{
parentData:{},
initParentData:function(parent){
this.parentData = parent.data;
return this;
},
initChild:function(){
console.log(this.parentData);
}
}
};
window.TestJS = new TestJS();
})(window);
如何使用第一种方式可以得到第二种方式的内容?
【问题讨论】:
-
因为
initChild中的TestJS不是不是window.TestJS... 和new TestJS().data中的data根据您的代码定义,将是在运行initData之前为空对象 -
顺便说一句,
(function (window){...}(window))毫无意义。如果您想明确访问全局对象,请使用 this,如:(function(window){...}(this))注意在非浏览器主机中,window 将是全局对象,而不是窗口对象。 -
@JaromandaX thx ,在第一个代码 initChild() 方法中,我可以得到这样的数据:console.log(window.TestJS.data.val_name_1);
-
@JaromandaX 我认为指出 为什么 TestJS 和 window.TestJS 在这种特殊情况下不同是很重要的。这是因为
var TestJS在闭包内创建了一个新的本地绑定。 -
这就是你发布答案而我只是发表评论的原因
标签: javascript prototype