简体   繁体   中英

console.log returns an additional undefined

I am trying to understand .bind and made the following code:

a simply object:

person = {
    name:"Joe",
    surname:"Something",
    tool:"gun",
    action: function(){
        console.log("shoot my wife");
    }
}

a function:

function police(){
    console.log("You are under arrest, " + this.name + " " + this.surname);
}

and binding the person object to the police function

var newPolice = police.bind(person);

And finally I console log it:

console.log( newPolice() );

I do get the desired string ("You are under arrest, Joe Something") but I also get an undefined and I have no idea where it is coming from. (In the code it is the console.log(newPolice()) that generates the undefined)

This has nothing to do with bind .

When you call newPolice() it logs the result of this:

 console.log("You are under arrest, " + this.name + " " + this.surname); 

When you call console.log( newPolice() ); , you now have two console.log statements which, between them, log:

  • The same thing as before
  • The return value of newPolice

newPolice doesn't have a return statement, so it returns undefined .

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