2012-07-12 47 views
0

如何在創建功能後編輯功能?如何在創建後編輯功能

function foo(a, b) { 
    this.c = a+b; 
} 

var bar = new foo(2,3); //result: {'c':5} 

//now I would like to create a new function, which is a bit different from the first 
foo2 = foo; 
foo2.d = a*b; //here I get an error: a is not defined 

bar2 = new foo2(3,4); 

不,我的意思是結果應該是這樣的:

function foo2(a, b) { 
    this.c = a+b; 
    this.d = a*b; 
} 
+0

無法更改構造函數。 [這個答案](http://stackoverflow.com/a/6529410/990877)可能會幫助你。 – PPvG 2012-07-12 17:07:24

回答

1

你不能做的正是你想要的東西,但也有其他方法可以做到你想要什麼。

function builder(fn, propertyName) { 
    return function() { 
    var args = arguments; 
    this[propertyName] = fn.apply(this, arguments); 
    this.change = function (otherFn, otherPropertyName) { 
     return builder(otherFn, otherPropertyName || propertyName); 
    } 
    } 
} 

var Foo = builder(function (a, b) { return a + b; }, "c"); 

var foo = new Foo(3, 4) 

var Foo2 = foo.change(function (a, b) { return a * b; }, "d"); 

var foo2 = new Foo2(3, 4) 

console.log(foo.c, foo2.d) // => 7 12 

這樣做的更好的方式是這樣的...

function Foo(a, b) { 
    var self = this; 
    this.add = function (name, fn) { 
    self[name] = fn.call(self, a, b); 
    } 
} 

var foo = new Foo(3, 4); 
foo.add("c", function (a, b) { return a + b; }); 
foo.add("d", function (a, b) { return a * b; }); 

console.log(foo.c, foo2.d) // => 7 1 
1

有沒有辦法來編輯功能,您可以通過在目前情況下分配等功能,以相同的名稱替換它或者你可以把它輕鬆地從外面修改:

function foo(a, b) { 
    this.c = this.op !== undefined ? this.op(a, b) : (a + b); 
} 

var bar = new foo(2, 3); // bar.c === 5 

foo.prototype.op = function(a, b) { 
    return a * b; 
} 

var bar2 = new foo(3, 4); // bar.c === 12 

這樣一來,你的函數或者是使用默認的代碼(A + b),或者也可以在任何時間重寫由定義運算功能原型。

+0

需要通過正在編輯的功能進行協作,儘管 – tucuxi 2012-07-12 17:12:25

+0

@tucuxi:的確如此,我在回答中添加了一句話,謝謝! – Tomek 2012-07-12 17:17:23

0

當您編寫foo2 = foo時,您只需爲foo調用foo2爲別名;沒有複製或覆蓋正在進行。當你寫foo2.d時,你指的是foo.d的另一個名字;和foo.d === undefined。另外,a和b只在foo的內部範圍內纔有意義(因此也是未定義的)。

你可以寫foo的一個新的定義,但是:當然

function foo(a, b) { 
    this.d = a*b; 
    this.c = a+b; 
} 

上一頁富對象將受到影響;而你的「foo2」會一直指向foo的前一個版本。

1

我想你正在嘗試的是JavaScript中的繼承?

// base class contains only "sum" method 
function foo(a, b) { 
    this.a = a; 
    this.b = b; 
} 

foo.prototype.sum = function(){ 
    return this.a + this.b; 
} 

// derived class contains new "multiply" method 
function foo2(a, b){ 
    foo.call(this, a, b); 
} 

foo2.prototype = new foo(); 

foo2.prototype.multiply = new function(){ 
    return this.a * this.b; 
} 

// test drive! 
var foo2Obj = new foo2(5, 4); 
console.log(foo2Obj.sum()); // 9 
console.log(foo2Obj.multiply()); // 20