【问题标题】:Why does javascript closure returns [Function (anonymous)]?为什么 javascript 闭包返回 [Function (anonymous)]?
【发布时间】: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


【解决方案1】:

在最后一行你没有调用函数。应该是console.log(a.getSecret());

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());

【讨论】:

    【解决方案2】:

    您收到此错误是因为您在 console.log 中显示函数本身,而不是其返回值。

    修复:将最后一行替换为这一行

    console.log(a.getSecret());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      相关资源
      最近更新 更多