2013-08-02 26 views
0

有點長鏡頭。但無論如何,要在構造函數的原型上獲得鏈式屬性,並且仍然將「this」上下文指向原始對象實例。例如:JavaScript - 原型上的鏈接屬性,帶有正確的'this'上下文

Array.prototype.$ = {}; 

Array.prototype.$.where = function(selector) { 
    console.log(this); 
    return; 
}; 

var myArray = [ 1, 2, 3 ]; 
myArray.$.where(); 

控制檯輸出{ where: [Function] }中,「這個」上下文指向 其中功能 $對象,而不是在陣列本身。

但是,如果我將其更改爲:

Array.prototype.where = function(selector) { 
    console.log(this); 
    return; 
}; 

var myArray = [ 1, 2, 3 ]; 
myArray.where(); 

它正確地輸出[ 1, 2, 3 ]

+1

「的‘本’上下文指向哪裏函數」 - 不,它指向' $'對象,包含'where'函數。 – basilikum

+0

啊,好點basilikum。更新。 –

回答

1

你不能做到這一點,但如果你不能改變最初的定義,一個可能的解決方法是:

//<definitions> 
Array.prototype.$ = {}; 

Array.prototype.$.where = function(selector) { 
    console.log(this); 
    return; 
}; 
//</definitions> 

Array.prototype.dollarCall = function(fName, arg) { 
    this.$[fName].call(this,arg); 
} 

var myArray = [ 1, 2, 3 ]; 
myArray.dollarCall('where'); 

我重複自己。這只是針對特定情況的解決方法。否則,你應該使用自己的第二個方法

如果你可以改變你的定義,另一種可能的解決方案:

Array.prototype.extend = function() { 
    var array = this; 
    this.$ = { 
     where : function() { 
      console.log(array); 
     } 
    } 
} 

var myArray = [ 1, 2, 3 ]; 
myArray.extend(); 
myArray.$.where() 
3

this在你的函數是myArray.$,這與Array.prototype.$完全相同。你可以執行console.log(myArray.$)console.log(Array.prototype.$),它們會打印出相同的結果myArray.$.where();

這是什麼意思?當你打電話給myArray.$.where();時,你實際上在做Array.prototype.$.where();。所以它的上下文(this)變成Array.prototype.$,所以它不會按照你的預期工作。


還有一件事:extending the DOM/built-in object prototype is generally considered harmful。我強烈建議嘗試另一種方式。

+0

我知道這是有害的,這就是爲什麼我試圖擴展它只有一個屬性,$財產。另外,我不想擴展Object本身,只是Array。 –

+0

我想出了這種方法http://jsbin.com/uwutaf/1/edit,它的工作原理。雖然語法有點醜陋。 –

1

我不認爲這有可能是這樣的:因爲$是一個普通的對象,它可以通過許多對象引用(即使壽」在這種情況下,只有一個,這就是Array.prototype.$),因此從內$有沒有辦法告訴您使用哪些引用來訪問它們。

我的意思是:

Array.prototype.$ = {}; 
someOtherObject = Array.prototype.$; 

Array.prototype.$.where = function(selector) { 
    console.log(this); 
    return; 
}; 

var myArray = [ 1, 2, 3 ]; 
myArray.$.where(); 
console.log(myArray.$) 
someOtherObject.where() 

由於話筒說,someOtherObjectmyArray沒有任何關係。

P.S.這就是說,我仍然覺得自己必須有一些簡單的方法來做到這一點沒有接口複雜進一步...

+0

我想出了這個http://jsbin.com/uwutaf/1/edit雖然我覺得語法有點醜,但它的工作原理。 –

+2

@SundayIronfoot這將創建一個完整的新對象,每次調用'$'時都包含所有函數。我認爲如果只是將函數添加到實例而不是原型中,除非可能同時創建大量數組,否則你會更好。 – basilikum