Assuming jquery is included:
function FixedPoint(bgWidth) {
this.bgWidth= bgWidth;
this.plot();
$(window).resize(this.plot);
}
FixedPoint.prototype.plot = function() {
console.log(this.bgWidth); //This is undefined when called by resize
}
var pt1 = new FixedPoint(1920);
When plot() is being called in the constructor or after the initialization everything is ok, but when plot() is being called by resize function, it can no longer access instance variables via 'this'.
I can call resize out side of the constructor to fix this, but want to have it in the class for tidiness.
$(window).resize(this.plot);
The method this.plot
is getting invoked from within the window
context. So this is the expected behavior. this
will point to the window object instead of FixedPoint
. You can use Ecmascript5 function.bind to explicitly bind the context.
$(window).resize(this.plot.bind(this));
With jquery you can use $.proxy to do the same thing.
Just to give more insight, this
context is set based on where the method was invoked from (except for the bound functions). Here this would have got invoked from within the resize
method of window object, where this
refers to window.
Another hacky way is to use anonymous callback function and use cached this variable.
function FixedPoint(bgWidth) {
this.bgWidth = bgWidth;
var self = this; //cache it here
$(window).resize(function () {
self.plot(); //invoke with self.
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.