【发布时间】:2020-04-25 09:18:27
【问题描述】:
来自medium,understand closures的代码
function Person(name) {
var secret = 'secret!';
this.name = name
this.setName = function(newName) { this.name = newName }
this.setNameToFoo = function() { this.name = foo }
this.getSecret = function() { return secret }
}
var a = new Person('Max');
console.log(a.name);
a.setName('Oliver')
console.log(a.name);
var foo = 'Foo';
a.setNameToFoo()
console.log(a.name);
console.log(a.getSecret);
输出
Max
Oliver
Foo
[Function (anonymous)]
一切都很好,除了最后一个。似乎本地绑定不可见。 为什么?
【问题讨论】:
-
为什么要分配 this.getSecret = function ,您只需像这样返回变量 this.getSecret = secret ,:-)
标签: javascript closures