2

I have declared a JavaScript object:

function A(name){
    this.name=name
}

A.prototype.test=function(){
    console.log(this.name);
};

as a simple example I have set up a button that if it's clicked should output a variable to the local console log:

<button id='test'>test</button>

the script:

var t=new A('hello');
$('#test').click(t.test);

when I click the button I want this.name to show (in this case 'hello'), but instead this refers to the clicked button, and not to the object I created.

this is a debugging script of course. In real life I'm binding a function to the window.resize event which will re-build a window on resizing.

There is a JSFiddle that shows the problem.

I have one solution for this, that is declaring the resize (or click function) in the constructor of the object and using an alternative name for this, like so (Here's the JSFiddle):

function A(name){
    this.name=name

    var self=this;
    $("#test").click(function(){
        console.log(self.name);
    });
}

but I'd rather use a prototype and bind the function in the object's constructor. How can I do this using prototypes?

patrick
  • 11,519
  • 8
  • 71
  • 80

1 Answers1

3

You can use bind, which will set the value of this ahead of time:

var t=new A('hello');
$('#test').click(t.test.bind(t));
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Thanks! This can even be called from within the object constructor: $("#test").click(this.test.bind(this)); Exactly what I was looking for! – patrick Nov 17 '15 at 14:07
  • 2
    @patrick What you just said doesn't make a lot of sense. That call is making sure that the `test` function is called with `t` as its `this` value. It's similar (not exactly the same) to calling `$('#test').click(function() { t.test() };` – Ruan Mendes Nov 17 '15 at 14:09
  • Juan, you're right, I tested the function and it worked like a charm! – patrick Nov 17 '15 at 14:12