2014-02-26 57 views
0

比方說,我有這樣的功能:擴展功能

function foo(){ 
    var myValue = 5; 
    var myOtherValue = 1; 
    return { 
     getValue: function(){ 
      return [myValue, myOtherValue]; 
     } 
    } 
} 

有沒有一種方法,我可以以某種方式延長/覆蓋此功能,無需觸摸原有的功能,這樣,當我打電話getValue()我得到[SOME OTHER VALUE I CHOOSE, myOtherValue]

如果不是,我可以在實例級別執行嗎?

var myFoo = new foo(); 
myFoo.getValue = function(){ 
    return [0, myOtherValue]; // how to I access myOtherValue? 
} 

回答

3

如果你不想修改富,你可以這樣做:

function foo(){ 
    var myValue = 5; 
    var myOtherValue = 1; 
    return { 
     getValue: function(){ 
      return [myValue, myOtherValue]; 
     } 
    } 
} 

var myFoo = new foo(); 
//move getValue to _getValue 
myFoo._getValue = myFoo.getValue; 

//do custom getValue 
myFoo.getValue = function(){ 
    return [0, myFoo._getValue()[1]]; 
} 
1

你不能。

myOtherValue僅限於foo的範圍內。


你可能要重寫這樣的事情:

function foo(){ 
    var myValue = 5; 

    return { 
     myOtherValue: 1, 
     getValue: function(){ 
      return [myValue, this.myOtherValue]; 
     } 
    } 
} 

然後你可以信息:

var myFoo = new foo(); 
myFoo.getValue = function(){ 
    return [0, myFoo.myOtherValue]; 
} 
+0

你可以請求代理到'foo',仍然能夠做到這一點。可能很困難,但這是可能的。 – squid314

+0

@ squid314你能解釋一下嗎? – qwertynl

+0

給我一點,我正在回答我自己的看法。 – squid314

0

你可以這樣做

function myFoo() { 
    var vals = foo().getValue(); 
    return { 
     getValue : function(){ 
      return [0, vals[1]] 
     } 
    } 
} 

vals[1]顯然是myOtherValue

1
function foo(){ 
    var myValue = 5; 
    var myOtherValue = 1; 
    return { 
     getValue: function(){ 
      return [myValue, myOtherValue]; 
     } 
    } 
} 

var myFoo = new foo(); 
var storeOriginal= myFoo.getValue; 
myFoo.getValue = function(){ 
    //your code 
    storeOriginal(); 
} 
1

您無法在閉包中訪問變量。但是,您可以定義新的功能委託給原有的功能進行訪問:

var myFoo = new foo(); 
myFoo.getValue = (function (original) { 
    return function(){ 
     var val = original(); 
     val[0] = 0; 
     return val; 
    }; 
}(myFoo.getValue)); 

下面是該解決方案的小提琴,所以你可以嘗試一下自己:http://jsfiddle.net/6Ux92/1/

1
function foo() { 
    .. original stuff .. 
} 


var hidden_foo = foo; 
function decorator() { 
    var internal = hidden_foo(); 

    // here is the proxy object 
    return { 
     getValue: function() { 
      return [SOME OTHER VALUE I CHOOSE, internal.getValue()[1]]; 
     } 
    } 
} 
// overwrite the original function with our decorated version 
foo = decorator; 
0

你可以包裝這個功能與裝飾功能:

var decorator = function() { 
    var someNewValue = ...; 
    var myOtherValue = foo().getValue()[1]; 
    return [someNewValue, myOtherValue]; 
} 
0

試試這個:

function foo(){ 
    this.myValue = 5; 
    var myOtherValue = 1; 
    return { 
     getValue: function(){ 
      return [this.myValue, myOtherValue]; 
     } 
    } 
} 

var bar = new foo(); 
bar.myValue = "whatever";