你不能完全按照自己的意愿去做,但是还有其他方法可以做你想做的事。
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