簡體   English   中英

為什么 javascript 閉包返回 [Function (anonymous)]?

[英]Why does javascript closure returns [Function (anonymous)]?

來自媒體的代碼,了解閉包

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

Output

Max
Oliver
Foo
[Function (anonymous)]

一切都很好,除了最后一個。 似乎本地綁定不可見。 為什么?

在最后一行,您沒有調用 function。 它應該是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());

您收到此錯誤是因為您在 console.log 中顯示 function 本身,而不是其返回值。

修復:用這一行替換你的最后一行

console.log(a.getSecret());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM