JavaScript,MooTools-类中的变量范围/覆盖全局变量

JavaScript,MooTools-类中的变量范围/覆盖全局变量,javascript,class,object,mootools,scope,Javascript,Class,Object,Mootools,Scope,有人能给我解释一下,为什么我可以通过在本地设置全局实例的方法值来覆盖它,为什么我不能对变量做类似的事情 使用窗口对象层次结构是否是访问变量的唯一方法?或者有没有更短的路 (function() { console.log(this); var someVar = this.someVar = false; var subClass = new Class({ test: false, setValue: function(value)

有人能给我解释一下,为什么我可以通过在本地设置全局实例的方法值来覆盖它,为什么我不能对变量做类似的事情

使用
窗口
对象层次结构是否是访问变量的唯一方法?或者有没有更短的路

(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()
    })
})()
(如果我理解正确的话)

这与Mootools或CLASE无关,@Felix_Kling已经给了你答案,但我将用一个简单的例子来说明:

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

我不确定这是否是您所问的=)希望这对您有所帮助

这与变量范围有关。 Javascript具有功能范围

这样做:

var someVar = this.someVar = false;
您正在声明一个局部变量someVar和一个全局变量(它被提升到窗口对象ie window.someVar),因为闭包中的这个变量引用全局范围ie window

所以当你写作时:

someVar = true;
您正在使用此新值覆盖局部变量

如果使用var关键字,则函数定义中声明的变量是该函数的局部变量:

(function () {
   var name = 'Mark';
})();
// Out here you cannot access name
console.log(name);

在一种情况下,您正在更改包含基元值的变量,而在另一种情况下,您正在更改对象的属性。原语值都是不可变的。谢谢,这对我帮助很大。=)