2012-08-14 196 views
0

console.log()執行WSFunctions[this.name]();將打印undentified。我想知道我是否能夠inheritDoThisAndThat在我的Call()函數。我不想以WSFunctions[this.name](this.params)的方式傳遞參數,因爲項目增長時可能會有超過this.params的通過。將參數傳遞給對象或繼承對象的函數?

function WS(name, params) { 
    this.name = name; 
    this.params = params; 
} 

WS.prototype.Call = function() { 
    if (typeof WSFunctions[this.name] !== "function") { 
     return false; 
    } 

    console.log(this.params); 
    WSFunctions[this.name](); 

    return true; 
} 

var WSFunctions = { 
    'ScreenRightGuest': function() { 
     // .. whatever .. 
     return true;   
    }, 
    'DoThisAndThat': function() { 
     console.log(this.params); 
     return true; 
    } 
} 


new WS('DoThisAndThat', { login: '123', pass: 'abc' }).Call(); 

在此先感謝 麥克

+0

或者你可能有不同的建議,如何構建,我剛剛開始使用JavaScript「類」。 – Mike 2012-08-14 14:51:09

+0

這與「類」或繼承或原型沒有任何關係,只與「this」和調用函數的工作方式有關, – 2012-08-14 14:56:31

+0

是的這是一個非常奇怪的模式。您正在構建對象的實例,並使用此對象的「屬性」引用該類型的「靜態函數」。 – dievardump 2012-08-14 14:56:33

回答

0

您可以明確設置什麼this應該是指在函數中調用.call[MDN].apply[MDN]

WSFunctions[this.name].call(this); 

這將調用WSFunctions[this.name]this被設置到什麼this指主叫方(在這種情況下,由new WS(...)創建的實例)。

也看看this page,它徹底解釋如何this的作品。

+0

當然,謝謝你這樣做,如果你能在第一篇文章中留言,我會很高興。 – Mike 2012-08-14 15:06:31