2012-05-08 36 views
2

我正在用幾個'modules'構建一個應用程序。每個模塊都需要一組類似的基本功能,所以我創建了一個基本模塊,每個模塊都將通過原型繼承繼承。基本模塊上的某些函數名稱相當長,而且由於這些函數經常使用,所以我想在每個模塊中分配較短的名稱,但這會導致'this'的值設置爲等於DOMWindow。原型繼承和'this'的值

請參閱下面的代碼:

var SAMPLEAPP = SAMPLEAPP || {}; 

//This is a base module that I want all other modules to inherit from 
SAMPLEAPP.Module = function(){ 

}; 

SAMPLEAPP.Module.prototype.someLongFunctionName = function(){ 
    console.log(this); 
}; 


//This is a module that inherits from the base module 
SAMPLEAPP.RouterModule= function(){ 
    var shortName = this.someLongFunctionName; 

    //This correctly logs 'SAMPLEAPP.RouterModule', but I would rather not type 
    //out this long function name each time I need to use the function 
    this.someLongFunctionName(); 

    //However, this code logs 'DOMWindow' when I would expect the value of 'this' 
    //to be the same as the direct call to this.someLongFunctionName 
    shortName(); 
}; 

SAMPLEAPP.RouterModule.prototype = new SAMPLEAPP.Module(); 


new SAMPLEAPP.RouterModule(); 

我的問題:我如何可以修改代碼,以便調用SHORTNAME()記錄SAMPLEAPP.RouterModule?如果可能的話,我寧願改變定義模塊的方式,而不是實際調用shortName(即shortname.call(this),這會破壞爲某些LongFunctionName創建別名的目的)

回答

2

正如其他人所說,你可以使用callapply(或者將工作,所不同的僅僅是如何將參數傳遞給函數) 。

或者,你可以使用ES5 bind方法,結合上下文的功能(在這種情況下,背景會this):

var shortName = this.someLongFunctionName.bind(this); 

然後,您可以撥打shortName像通常那樣:

shortName(); 

這是working example。而這裏的MDN文章的最相關的部分:

的bind()函數創建一個新的功能(綁定功能)與 相同的函數體(在ECMAScript中5項內部調用屬性)作爲 功能它被綁定到bind(), 的第一個參數,它不能被覆蓋,這個值被調用(綁定函數的目標 函數)。

+0

謝謝。這可能是答案,我只需要評估我的代碼和本文中描述的部分實現是否可以在IE8 –

+0

中工作@MarkBrown - MDN文章中描述的墊片應該可以做到。或者,查看[ES5 shim](https://github.com/kriskowal/es5-shim/),但如果這是您需要的唯一ES5功能,則可能會過大。 –

0

您可以將呼叫更改爲shortName();shortName.call(this);

這是javascript是一個小竅門。基於上下文。

+0

感謝。請參閱我的編輯,我寧願一個解決方案,不需要更改我稱爲shortName() –

1

您可以使用調用/應用函數將「this」上下文傳遞給方法調用。在你的情況下,它可以是

shortName.apply(this); 

OR

shortName.call(this); 
+0

謝謝。請參閱我的編輯,我更喜歡不需要改變我稱爲shortName() –

+0

的解決方案如果您的意圖是提供較長的函數名稱,那麼如何使用[module pattern](http: //www.klauskomenda。com/code/javascript-programming-patterns /#module)或[揭示模塊模式](http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing),甚至是[揭示原型模式] (http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx)? –