gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:11:27 27 4
gpt4 key购买 nike

我正在尝试学习如何在另一个 .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 方法给出了 not a function

我现在要回家,按照@Liam 的建议阅读更多关于关闭的信息,然后看看明天会发生什么。

最佳答案

好的,让我们分解一下

getterTest = (function() {});

getterTest 是一个函数指针。也就是说,它是一个包含un-envoked 函数的变量。

如果我这样做:

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

我调用函数。

如果我这样做:

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

result 包含从 getterTest 函数返回的函数,即包含函数和可获取 x 属性的对象 ({})

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

get x() {
return _x;
}
}

所以我可以这样做:

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

长话短说

虽然是真的;你想要的是让 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,因为它的范围是函数。本质上,这就是关闭点。将事物保持在范围内并保持“全局上下文”干净。


仅供引用

您可能会注意到我在上面交替使用了“函数”和“对象”。不习惯 Javascript 的人会觉得这很奇怪,但这是有充分理由的。在 Javascript 中 a function is an object o_O

这也是您在此尝试实现的目标之一。基本上都是关于 encapsulation

关于javascript - 访问javascript对象的属性返回undefined,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338045/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com