[英]How to access from 'private method' to 'public variable', in Javascript class
首先,請參閱我的代碼plz。
function test(){
this.item = 'string';
this.exec = function(){
something();
}
function something(){
console.log(this.item);
console.log('string');
}
}
然后我制作了類並調用“ exec函數”,就像這樣的代碼
var t = new test();
t.exec();
但是結果是...
undefined
string
我想從某種功能訪問test.item。
你有什么解決辦法嗎?
你需要調用something
與apply
,使this
是正確設置里面something
:
function test(){
this.item = 'string';
this.exec = function(){
something.apply(this);
}
function something(){
console.log(this.item);
console.log('string');
}
}
正如@aaronfay指出的,發生這種情況是因為this
並不涉及new test()
創建的對象。 您可以在此處了解更多信息,但一般規則是:
如果在一個object
上調用了一個object
,則this
引用該object
。 如果一個函數被單獨調用(就像您的代碼中那樣),則this
引用的是全局對象,在瀏覽器中是window
。
您有很多選擇,但我建議選擇最后一個。
var item = 'string'
要么
this.exec = function(){
something.apply(this, []);
}
要么
var that = this;
function something(){
console.log(that.item);
console.log('string');
}
something()
this.item
不是您認為的那樣。
在this
值是不同的。 在這種情況下,它是全局對象。
我認為,最好的解決方案是使用this
聲明一個變量,該變量可在內部函數中訪問。
function test() {
var that = this; // a reference to 'this'
function something() {
console.log(that.item); // using the outer 'this'
console.log('string');
}
this.item = 'string';
this.exec = function(){
something();
}
}
為什么不只定義如下內容:
function test(){
this.item = 'string';
this.exec = function(){
this.something();
}
this.something = function(){
console.log(this.item);
console.log('string');
}
}
var t = new test();
t.exec();
// output:
// string
// string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.