访问javascript对象的属性返回undefined,为什么?

时间:2016-03-31 15:47:32

标签: javascript closures

我正在尝试学习如何在另一个.js文件中创建JavaScript类,并从其他任何地方访问它。我已经阅读了一些例子,但似乎无法完全理解它。

例如,如何访问以下内容:

//code in file2.js
getterTest = (function() {
  var _x = 15;

  return {
    doSomething: function() {
      _x += 5;
    },

    get x() {
      return _x;
    }
  }
});

//code in file1.js
console.log(getterTest._x); //undefined
console.log(getterTest.x); //should give 15
getterTest.doSomething();
console.log(getterTest.x); //should give 20

但这一切都给了undefined,而.doSomething方法给了不是函数

我现在回家,阅读更多有关关闭的信息,正如@Liam建议的那样,明天会发生什么。

3 个答案:

答案 0 :(得分:2)

好的,让我们打破这个

getterTest = (function() {});

getterTest是一个函数指针。即它是一个包含 un-envoked 函数的变量。

如果我这样做:

getterTest = (function() {});
getterTest();

我调用了这个函数。

如果我这样做:

getterTest = (function() {});
var result = getterTest();

result包含getterTest函数返回的函数,即包含函数和gettable x属性的对象({}

result = {
    doSomething: function() {
       _x += 5;
    },

    get x() {
        return _x;
    }
}

所以我可以这样做:

getterTest = (function() {});
var result = getterTest();
result.x;

TL; DR

真的;你想要的是getterTest像这样工作:

getterTest = function() {
var _x = 15;

return {
    doSomething: function() {
       _x += 5;
    },

    get x() {
        return _x;
    }
}
}();
//invoke the function and store this in your variable by adding () above    

//code in file1.js
//console.log(getterTest._x);         //this is private so can't be accessed (you can only access things that are returned)
console.log(getterTest.x);         //should give 15
getterTest.doSomething();
console.log(getterTest.x);        //should give 20

Fiddle

你不能在闭包之外访问_x,因为它的作用域是函数。这基本上就是关闭点。保持范围并保持"全球背景"干净。

FYI

你可能会注意到我有点使用"功能"和"对象"在上面可互换。不习惯Javascript的人发现这很奇怪,但有充分的理由。在Javascript a function is an object o_O

这也是你想要在这里实现目标的原则之一。它基本上都与encapsulation

有关

答案 1 :(得分:0)

请做,

//code in file2.js
getterTest = (function() {
    var _x = 15;
    return {
        doSomething: function() {
           _x += 5;
        },

        get x() {
            return _x;
        }
    }
}()); // added '()'


//code in file1.js
console.log(getterTest._x);         //undefined
console.log(getterTest.x);         //15
getterTest.doSomething();
console.log(getterTest.x); 

答案 2 :(得分:-1)

您需要实例化该类,然后调用这些函数。

var g = getterTest(); 
console.log(g.x);         //15
g.doSomething();
console.log(g.x); //20

如果您在每次通话时拨打getterTest(),它将始终获得该课程的新版本

console.log(getterTest().x);         //15
getterTest().doSomething();
console.log(getterTest().x); //15

我知道这对你来说并不理想。但这是调用file2.js中函数的正确方法 其他选择是重写file2.js
祝你好运!

相关问题