Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the goal of self.self == self check in JavaScript?

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.

like image 731
user50311 Avatar asked Oct 17 '15 01:10

user50311


People also ask

What is the use of self in JavaScript?

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.

What is self variable in JavaScript?

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.

Why self is needed instead of this in JavaScript?

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.

What is let self this?

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.


1 Answers

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.

like image 198
Bergi Avatar answered Sep 18 '22 17:09

Bergi