简体   繁体   中英

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

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

Output

Max
Oliver
Foo
[Function (anonymous)]

Everything is OK,except the last one. It seems that local bindings is not visible. Why?

At the last line you are not calling the function. It should be 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());

You're getting this error because you're displaying the function itself in console.log, not its returning value.

Fix: Replace your last line with this one

console.log(a.getSecret());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM