类内部的JavaScript变量始终未定义 [英] JavaScript variable inside class is always undefined
问题描述
我有一个像这样的JavaScript类:
I have a JavaScript class like this:
Dog = (function() {
var name;
function setName(_name) {
name = _name;
}
return {
setName: setName,
name: name
};
})();
当我跑步时:
Dog.setName('Hero');
Dog.name
始终未定义.
我当然缺少有关JS作用域的信息,但是呢?
I am certainly missing something about JS scoping, but what?
推荐答案
您将返回一个对象,该对象的name
属性在该时间点的值为name
(未定义) ).当更新IIFE中的name
变量时,返回对象的name
属性不会以某种方式动态更新.
You are returning an object where name
property has a value of name
at that point in time (which is undefined). The name
property of the returned object is not somehow dynamically updated when the name
variable inside the IIFE is updated.
有很多方法可以处理您似乎想做的事情.这是一个:
There are many ways to handle what you appear to be wanting to do. Here's one:
Dog = (function() {
var name;
function setName(_name) {
name = _name;
}
return Object.defineProperties({}, {
setName: { value: setName },
name: { get: function() { return name; } }
});
})();
这将name
保留为私有变量,只能通过setName
进行设置,但是提供了用于获取其值的getter属性.
This keeps name
as a private variable, which can only be set via setName
, but provides a getter property for obtaining its value.
另一个答案中提出的替代方案是等效的,只是写法不同:
The alternative proposed in another answer is equivalent, just a different way of writing it:
return {
setName: function(n) { name = n; },
get name: function() { return name; }
};
次要点,但在此特定情况下,您不需要在IIFE上加上括号:
Minor point, but in this particular context you don't need parentheses around your IIFE:
Dog = function() { }();
可以正常工作.
这篇关于类内部的JavaScript变量始终未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!