一个奇怪的问题:关于JavaScript的原型关于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' ...和''TestJS()。data'中的'data',根据您的代码的定义,直到'initData'运行的对象 –
顺便说一句,'(函数(窗口){...}(窗口))'是毫无意义的。如果你想明确地访问全局对象,使用* this *,如:(function(window){...}(this))'注意在非浏览器主机中,* window *将是全局对象而不是一个Window对象。 – RobG
@JaromandaX thx,在第一个代码的initChild()方法中,我可以得到如下的数据:console.log(window.TestJS.data.val_name_1); –