For the following code, I'm expecting "Jupiter" for the console 2 and 3, but getting the one bound to the global window object, even though I passed a different context.
function otherScope () {
this.sectionHeight = "Jupiter"
}
(function () {
var sectionHeight = "Mars";
(function () {
setTimeout(function () {
console.log('console 1', sectionHeight)
})
}())
}())
window.sectionHeight = "cool!";
(function () {
setTimeout(function () {
console.log('console 2', sectionHeight)
})
}.bind(otherScope)())
setTimeout(function () {
console.log('console 3', sectionHeight)
}.bind(otherScope))
setTimeout(function () {
console.log('console 4', sectionHeight)
})
Te otherScope is a function and is not a Object with properties. You have to do a new for this. So:
var x = new otherScope();
x.sectionHeight;
Next, the scope of this only reaches the current scope. The setTimeout creates a new scope. Therefor we need to do another binding. Or creating a variable inside the first scope outside the setTimeout.
Some example (variable within scope):
(function () {
var theScope = this;
setTimeout(function () {
console.log('console 2', theScope.sectionHeight)
});
}.bind(new otherScope())())
Some example (another bind):
(function () {
setTimeout(function () {
console.log('console 2', this.sectionHeight)
}.bind(this)); // Pass the context to the new scope
}.bind(new otherScope())())
bind sets the value of this for the function on which it is called (which I shall refer to as x).
It does not:
y) even if y is called by xx or any function called by x.There is no way to change the scope that a function exists in. That is determined solely by where it is declared.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With