如何在创建函数后编辑它?
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 :(得分: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 :(得分: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),要么可以通过在原型中定义op函数随时覆盖它。
答案 2 :(得分: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
答案 3 :(得分: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;
}
以前的foo对象当然不会受到影响;而你的“foo2”将继续指向foo的先前版本。