chalo chalo - 1 year ago 66
jQuery Question

Lost the scope of of a function inside a object

I have a problem, I'm losing reference to a property of an object ana when it runs within an event


As I can do to keep the scope.


var testObject = {

init: function () {
this.divOriginal = $('.selector-tag');

resizeNow: function () {
//some another code here....
$(window).resize(this.resizeUpdate.bind(this)); //without bind(this) the scope is window

resizeUpdate: function() {
var scrollWrapper = $(this)[0].divOriginal;//the only way to refer to the divOriginal
scrollWrapper.css('border','1px solid red');


There is a cleaner way to access the object's attributes?

Answer Source

You can simply access the object using this instead of $(this) since you bound your object to the method called by the event handler.

See the MDN docs on Function.prototype.bind() :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download