javascript - Error returning an object attribute in JS -
function objecte(name){ this.name=name; } objecte.prototype.look=function(){ return function(){ alert(this.name); }; }
i'm trying access object's attribute when call function, alerts undefined.
extintor = new objecte("extintor"); $(document).on('dblclick',"#extintor",extintor.look());
this
not lexically defined. need capture value in order ensure returned function can use it.
objecte.prototype.look=function(){ var self = this; return function() { alert(self.name); }; }
you can use $.proxy
objecte.prototype.look=function(){ return $.proxy(function() { alert(this.name); }, this); }
or .bind()
in modern browsers
objecte.prototype.look=function(){ return function() { alert(this.name); }.bind(this); }
Comments
Post a Comment