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?