Reputation: 40719
How to edit a function after it's created?
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);
No, I mean the result should be this:
function foo2(a, b) {
this.c = a+b;
this.d = a*b;
}
Upvotes: 0
Views: 83
Reputation: 4229
You can't do exactly what you want, but there are other ways to do what you want.
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
A better way of doing this is like this...
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
Upvotes: 1
Reputation: 32758
I think what you are trying is inheritance in 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
Upvotes: 1
Reputation: 805
There's no way to edit function, you can either replace it by assigning other function to the same name in the current context, or you can make it easily modifiable from the outside:
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
This way, your function is either using default code (a + b), or it can be overriden at any time by defining op function in the prototype.
Upvotes: 1
Reputation: 17945
when you write foo2 = foo, you are just making an alias for foo called foo2; no copy or overwrite is going on. When you write foo2.d, you are referring to foo.d by another name; and foo.d === undefined. Also, a and b make sense only in the inner scope of foo (and are therefore also undefined).
You could write a new definition for foo, however:
function foo(a, b) {
this.d = a*b;
this.c = a+b;
}
Previous foo objects would of course be unaffected; and your "foo2" would keep on pointing to the previous version of foo.
Upvotes: 0