2011-12-24 36 views
0

是否有可能在JavaScript中設置方法內的屬性?方法的javascript屬性

例如

function Main() { 

    this.method = function() { 
     this.parameter = 'something_relevant' 
    } 
} 

var p = new Main() 
p.method() 
console.log(p.method.parameter) 

我嘗試這樣做,它記錄 '未定義'。它是關於範圍的嗎?

+0

那是因爲你'method'調用是異步的,如果你把裏面的''console.log'的this.method'分配後它會奏效。 – Cyclonecode 2011-12-24 14:58:19

+0

@Krister Andersson:真的,這裏沒什麼異步。 – pimvdb 2011-12-24 15:00:50

回答

3

Inside 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' 

後,您應該決定是否需要對功能特性對象或對象。請注意,函數對象可能由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. 
+0

謝謝你延長你的回答,基本上我需要一個描述方法的屬性,所以我可以說它與'class'有關(請原諒這個詞一個JavaScript上下文) – fatmatto 2011-12-24 15:27:19

2

函數是對象基本上,所以只是把它就像你得到它:

this.method = function() { 

}; 

this.method.parameter = 'something_relevant'; 

而且,表情後不排除分號。

+0

謝謝你,對不起分號,我在發帖的時候忘了他們 – fatmatto 2011-12-24 15:10:57