0

I was checking ejs layout code of sails.js and saw the line that says delete window.self

<% /* Delete the global `self` to help avoid client-side bugs.
(see https://developer.mozilla.org/en-US/docs/Web/API/Window/self) */ %>

<script>delete window.self;</script>

I tried searching for to find an answer of why would we delete the window.self but could not find an answer. What is the rationale behind adding this line?

Edit: The code exist at line no. 137 here: https://github.com/mikermcneil/ration/blob/master/views/layouts/layout.ejs

Masade
  • 715
  • 1
  • 11
  • 29
  • 3
    I don't see it mentioned anywhere else. If no one knows, maybe ask whoever added that line? (it doesn't sound like a normal good thing to do) – CertainPerformance Dec 25 '18 at 18:29
  • If I had to guess it's done to "help avoid client-side bugs". There is also an attached link explaining it further... Not sure what the client-side bugs are but it most likely has to do with how browsers support self. – Matthew Ludwig Dec 25 '18 at 18:30
  • @matthew ... but ... that link is dead and [Window.self](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) doesn't contain any hint on why it is bad. – Jonas Wilms Dec 25 '18 at 18:35
  • That link is alive and well, your link even links right back to it haha. And while it doesn't expressly say why it is bad, it states that window.self and window are interchangeable. From there you can then get to the logic that the current top answer has, which is that the variable is pointless and clogs up the global namespace. – Matthew Ludwig Dec 25 '18 at 18:48
  • Please have a look at line number 137 in the following code: https://github.com/mikermcneil/ration/blob/master/views/layouts/layout.ejs – Masade Dec 25 '18 at 19:25

1 Answers1

5

The only explanation that would make sense to me would be:

To access the correct "this" inside a callback it is common practice to store a self reference:

 var self = this;
onSomething(function() {
  self.doSomething();
});

Now imagine someone forgot the first line, then self.doSomething() would say "doSomething" is not a function which is certainly missleading. If window.self gets deleted it'll say self is not defined, which is way more helpful.

... however it would be better to not name it self here...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    Or to use more modern practices like passing an arrow function and allowing a transpiler to make it backwards compatible... – Patrick Roberts Dec 25 '18 at 18:44
  • Can you please look at the ref in line no. 137 in the code: https://github.com/mikermcneil/ration/blob/master/views/layouts/layout.ejs – Masade Dec 25 '18 at 19:27