Reputation: 12378
How do I apply the context of functions to any javascript object? So I can change what "this" means in the functions.
For Example:
var foo = {
a: function() {
alert(this.a);
},
b: function() {
this.b +=1;
alert (this.b);
}
var moo = new Something(); // some object
var moo.func.foo = foo; // right now this is moo.func
// how do I apply/change the context of the foo functions to moo?
// so this should equal moo
moo.a(); // this should work
Upvotes: 1
Views: 74
Reputation: 179046
You can just set the function on moo
:
var moo = new Something();
moo.a = foo.a;
moo.a();
...but if you want it inherited by all instances of Something
, you'll need to set it on Something.prototype
:
var moo;
Something.prototype = foo;
moo = new Something();
moo.a();
You have some issues in your definitions of foo.a
and foo.b
, as they both are self-references this.b +=1
will especially cause issues, so you may want to change the functions to something like this._b +=
and alert(this._b)
, or use differently named functions.
Upvotes: 2