window
object, since all code runs in its context.<script> alert (location); // tell window.location </ script>
window
(I’m not talking about the fact that they are evil, break encapsulation and all that).function foo () { a = 2; b = 3; return a + b; } alert (a); // undefined a = 'very important'; alert (a); // very important foo (); alert (a); // 2
var
keyword.var a = 2;
function foo () { var a = 2; var b = 3; return a + b; } alert (a); // undefined var a = 'very important'; alert (a); // very important foo (); alert (a); // very important
window
property:function foo () { var location = 'location'; alert (location); // returns 'location' alert (window.location); // returns window.location window.a = 'variable from function'; } alert (a); // undefined foo (); alert (a); // variable from function
function alertOnTimeout (message, timeout) { return setTimeout (function () { // message will be available in an unnamed function passed to the timeout alert (message); }, timeout); }
eval()
- does not fall under this rule, the code is executed in the scope where it is defined.function myObject () { var property = 0; // By itself, property will be available only inside the object. }
if
(hello, Pascal). Therefore, it is most convenient to declare variables at the beginning of a function.this
this
? And the fact that this variable automatically appears in the methods of objects and overwrites the value of this from the previous scope. The solution is simple - reassign its value to another variable.$ ('div.with-links'). click (function () { var theDiv = this; // store the value of this $ (this) .find ('a'). click (function () { alert ($ (this) .attr ('href')); // this is a link theDiv.remove (); // and the Div is still a div }); });
function myObject () { var _this = this; // save the link to the parent object var linkRemoved = false; $ ('a'). click (function () { $ (this) .remove (); // this is the link object _this.linkRemoved = true; // _this is the parent object }); }
Source: https://habr.com/ru/post/78991/
All Articles