backbone.js starts with:
//Establish the root object, `window` (`self`) in the browser, or `global` on the server.
//We use `self` instead of `window` for `WebWorker` support.
var root = (typeof self == 'object' && self.self == self && self) ||
(typeof global == 'object' && global.global == global && global);
What is self.self == self
for? When can it be false?
Same about global.global == global
.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
Actually self is a reference to window ( window. self ) therefore when you say var self = 'something' you override a window reference to itself - because self exist in window object.
var self = this; In the JavaScript, “self” is a pattern to maintaining a reference to the original “this” keyword and also we can say that this is a technique to handle the events.
let a = 2; //this will never change let _self = this //_self will never change as it's your variable. Now when you call your function and it looks for _self. it knows exactly what you are talking about.
function Mistake(x);
self = this;
x.on("event", function() {
console.log(self);
});
}
new Mistake(…);
Did you spot it? Now we've got a global self
that is not the self
that backbone expects. So it checks whether self
actually is the global object, which is likely to be the case when self
is an object and the object has the "global variable" self
as a property that points to the object itself.
Same for global
.
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