[英]javascript properties of methods
是否有可能在javascript中設置方法內部的屬性?
例如
function Main() {
this.method = function() {
this.parameter = 'something_relevant'
}
}
var p = new Main()
p.method()
console.log(p.method.parameter)
我試過了,它記錄為“未定義”。 關於范圍嗎?
在method()
內部,您要設置在其上調用方法的對象的屬性,而不是在表示該方法的函數對象上的屬性。
這顯示了方法內部的區別:
this.method = function() {
this.parameter = 'abc'; // Set parameter on the object on which method() is called
this.method.parameter = 'xyz'; // Set parameter on the object representing the method itself
};
這表明在調用方法后訪問屬性的區別
p.method();
console.log(p.parameter); // Display property of the object p, equals 'abc'
console.log(p.method.parameter); // Display property of the function object representing method(), equals 'xyz'
您應該決定是否需要函數對象或p
對象上的屬性。 注意,函數對象可以由Main()
構造函數創建的許多對象共享。 因此,它的行為與類似於C ++或Java的靜態成員的行為類似。
如果打算使用在對象上定義的屬性,則代碼應類似於以下內容:
function Main() {
this.method = function() {
this.parameter = 'something_relevant'; // Set property on object on which method() is called.
};
}
var p = new Main();
p.method();
console.log(p.parameter); // Read property from object p.
如果打算使用在表示method()
的函數對象上定義的屬性,則代碼應類似於以下內容:
function Main() {
this.method = function() {
this.method.parameter = 'something_relevant'; // Set property on function object representing method().
};
}
var p = new Main();
p.method();
console.log(p.method.parameter); // Read property from the function object.
函數基本上是對象,所以只要像得到它一樣進行設置即可:
this.method = function() {
};
this.method.parameter = 'something_relevant';
另外,不要在表達式后消除分號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.