你不能做的正是你想要的东西,但也有其他方法可以做到你想要什么。
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