我有一個JavaScript getter方法,像這樣:的JavaScript getter方法
function passTags()
{
var tags = document.getElementById('tags').value;
this.getTag=function()
{
return this.tags;
}
}
我怎麼稱呼呢?
我有一個JavaScript getter方法,像這樣:的JavaScript getter方法
function passTags()
{
var tags = document.getElementById('tags').value;
this.getTag=function()
{
return this.tags;
}
}
我怎麼稱呼呢?
看起來你已經設置了一個構造函數,所以它會像這樣
var t = new passTags;
t.getTag();
this.tags
是沒有定義的,所以t.getTag()
將返回undefined
。如果你的意思是它返回的tags
值,然後將其更改爲
function passTags() {
var tags = document.getElementById('tags').value;
this.getTag = function() {
return tags;
}
}
記住儘管這一次拍攝的構造函數已經執行將不會更新的價值,因爲這example will demonstrate。還有一個建議是使用Pascal大小寫來表示函數名,以便清楚它是一個構造函數。
雖然你現在已經設置好了代碼,但如果它不是一個構造函數,那麼你首先必須執行passTags
函數。這將在全局範圍內定義一個函數getTag
,然後可以執行該函數。這將返回undefined
,但this.tags
爲undefined
。
謝謝Russ,這是很棒的幫助 – raoulbia 2011-04-03 16:44:04
你不應該定義爲tags
但var tags = ...
作爲this.tags = ...
- 編輯
拉斯的解決方案是 '好':tags
現在是私有的。
我會說'getTag()',參見http://javascriptgarden.info/#function.this。 – 2011-04-03 16:25:06
@Jakub,getTag沒有爲passTags()函數之外的任何人定義,所以它不會被識別。我需要使用點符號,但我不確定所需的確切語法 – raoulbia 2011-04-03 16:27:23
那麼,如果您調用'passTags()',那麼'getTag()'應該在全局範圍內定義。 – 2011-04-03 16:28:37