I have a constructor object. Inside this constructor i have two functions. One is called window.onresize and the other one is onBrowserResize. Now i want to call onBrowserResize inside the window.onresize function. How do i do this?
function MyObject() {
window.onresize = function(event) {
this.onBrowserResize();
}
this.onBrowserResize = function() {
}
}
I would like to have the function public so i can call it like this: object.onBrowserResize();
If I make the function private like this: var onBrowserResize = function() then I cannot access it outside the scope.
Anyone has an idea how to do it? I’m probably just a bit confused about the scoping in objects.
In JavaScript, the value of
thisis determined depending on how the function is called. See the MDN article onthisfor details.Your question is missing some details. My answer is assuming you have something like this:
Which is instanced like this:
Here are some of ways to achieve that.
1. Just passing this.onBrowserResize as the event handler (the simplest way to go, if all your onresize handler does is call
onBrowserResize):2. Caching a reference to the local
this:3. Fixing the value of
thiswithFunction.prototype.bind: