JavaScript, MooTools - Variable scope in Class/overwrite global variable
Can somebody explain me, why I am开发者_开发问答 able to overwrite a method value of a global instance by just setting its value locally and why I am not able to do something similar with variables?
Is the only way to access the variable to use the window
object hierarchy? Or is there maybe a shorter way?
(function() {
console.log(this);
var someVar = this.someVar = false;
var subClass = new Class({
test: false,
setValue: function(value) {
this.test = value
}
});
var subPub = this.subPub = new subClass();
var MainClass = new Class({
rewriteVar: function() {
console.log("someVar = " + someVar); // returns global value
console.log("subPub.test = " + subPub.test); // returns global value
someVar = true;
console.log("someVar local: " + someVar); // returns new local value
console.log("someVar global: " + window.someVar); // returns old global value
subPub.setValue(true);
console.log("subPub.test local: " + subPub.test); // returns new local value
console.log("subPub.test global: " + window.subPub.test) // returns new global value
}
});
/* var someObj = this.someObj = {};
var someVar = someObj.someMeth = false;
// And why is this possible?
var MainClass = new Class({
rewriteVar: function() {
someObj.someMeth = true;
console.log(window.someObj.someMeth); // returns new global value
}
}); */
window.addEvent("load", function() {
var test = new MainClass();
test.rewriteVar()
})
})()
This is to do with variable scope. Javascript has functional scope.
So by doing:
var someVar = this.someVar = false;
You are declaring a local variable someVar and a global variable (which gets hoisted to the window object ie window.someVar), as this within your closure referes to the global scope ie window.
So when you write:
someVar = true;
You are overwriting the local variable with this new value.
Variables declared within a function definition are local to that function if you use the var key word:
(function () {
var name = 'Mark';
})();
// Out here you cannot access name
console.log(name);
(if i understood correctly the problem)
It has nothing to do with Mootools or the clases, @Felix_Kling already gave you the answer but I will ilustrate it with a simple example:
var aObj = bObj = {}; //since bObj is an 'object', aObj will store the objects reference
aObj.foo = "bar";
console.log(aObj.foo);
console.log(bObj.foo);
// output:
// "bar"
// "bar"
var a = b = 1; //since 'b' is primitive, 'a' will not store a reference of 'b', it will only copy it's value
a = 0;
console.log(a);
console.log(b);
// output:
// 0
// 1
i'm not really sure if this is what you were asking =) Hope this helps
精彩评论