1

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
0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I think the [[prototype]] route is desired; it looks like a jQuery-emulation approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.