[英]In OPP JS can you access a method declared inside a prototype function from the constructor?
[英]How can I access a variable declared in the constructor from a method?
class X {
constructor (e) {
let someVar = e;
}
SomeMethod () {
console.log(this.someVar);
}
}
它給了我 undefined,那么我怎樣才能獲得 "someVar" 的值?;
在構造函數中,而不是let
使用this
:
constructor (e) {
this.someVar = e;
}
我強烈建議學習更多關於 javascript 中變量作用域的知識。 你可以參考這個帖子。
另外,如果您想了解更多關於 javascript class
的信息,請參閱這篇不錯的帖子。
遵循一個完整的工作示例:
class X { constructor (e) { this.someVar = e; } SomeMethod () { console.log(this.someVar); } } const obj = new X("Some text"); obj.SomeMethod();
class X { constructor (e) { this.someVar = e; } SomeMethod () { console.log(this.someVar); } }
在 JavaScript 中,可以在constructor
函數中使用this
關鍵字聲明對象字段。 因此,您的someVar
只是構造函數范圍內的局部變量。
你需要這樣做:
class X {
constructor (e) {
this.someVar = e; //Now, someVar is a proper field of any object instance of X
}
SomeMethod () {
console.log(this.someVar);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.