2014-02-26 218 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";