JavaScript variable inside class is always undefined
问题 I have a JavaScript class like this: Dog = (function() { var name; function setName(_name) { name = _name; } return { setName: setName, name: name }; })(); When I run: Dog.setName('Hero'); Dog.name is always undefined. I am certainly missing something about JS scoping, but what? 回答1: 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