我试图理解.bind并编写了以下代码:
一个简单的对象:
person = {
name:"Joe",
surname:"Something",
tool:"gun",
action: function(){
console.log("shoot my wife");
}
}
一个函数:
function police(){
console.log("You are under arrest, " + this.name + " " + this.surname);
}
并将 person 对象绑定(bind)到警察功能
var newPolice = police.bind(person);
最后我控制台记录它:
console.log( newPolice() );
我确实得到了所需的字符串(“你被捕了,Joe Something”),但我也得到了一个未定义的字符串,我不知道它来自哪里。 (在代码中,是console.log(newPolice())生成了未定义的内容)
最佳答案
这与bind
无关。
当您调用 newPolice()
时,它会记录以下结果:
console.log("You are under arrest, " + this.name + " " + this.surname);
当您调用 console.log( newPolice() );
时,您现在有两个 console.log
语句,它们之间,日志:
- 和以前一样
newPolice
的返回值
newPolice
没有 return
语句,因此它返回 undefined
。
关于javascript - console.log 返回一个额外的未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34974308/