你不能做的正是你想要的東西,但也有其他方法可以做到你想要什麼。
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
無法更改構造函數。 [這個答案](http://stackoverflow.com/a/6529410/990877)可能會幫助你。 – PPvG 2012-07-12 17:07:24