提问人:shiksnosparnis 提问时间:12/22/2021 更新时间:12/22/2021 访问量:111
函数绑定不起作用,返回 undefined
Function binding does not work, returns undefined
问:
所以我创建了两个对象:person 和 Tim。
我想将 logInfo 函数绑定到 Tim,但是当我用绑定调用它时,它会一直给我:
- 未定义的作业
- 未定义的电话
代码如下:
function hello() {
console.log('Hello')
}
const person = {
firstNAme: 'A',
age: 26,
sayHello: hello,
sayHelloWindow: hello.bind(document),
logInfo: function (job, phone) {
console.group(`${this.firstNAme} info: `)
console.log(`name is: ${this.firstNAme} and the age is: ${this.age}`)
console.log(`Job is: ${this.job}`)
console.log(`Phone is: ${this.phone}`)
console.groupEnd()
}
}
const Tim = {
firstNAme: 'Tim',
age: 22
}
const infoTim = person.logInfo.bind(Tim)
infoTim('clown', '100100-10010') // returns undefined values, why?
我似乎错过了什么吗? 先谢谢你!
答:
2赞
Pranay Binju
12/22/2021
#1
在函数中,remove for 和 因为它们通过参数被接受,并且不是对象的属性。 总是引用当前对象并指向对象的属性。logInfo
this
job
phone
Tim
this
this.something
参考更新的代码
function hello() {
console.log('Hello')
}
const person = {
firstNAme: 'A',
age: 26,
sayHello: hello,
sayHelloWindow: hello.bind(document),
logInfo: function (job, phone) {
console.group(`${this.firstNAme} info: `)
console.log(`name is: ${this.firstNAme} and the age is: ${this.age}`)
console.log(`Job is: ${job}`)
console.log(`Phone is: ${phone}`)
console.groupEnd()
}
}
const Tim = {
firstNAme: 'Tim',
age: 22
}
const infoTim = person.logInfo.bind(Tim)
infoTim('clown', '100100-10010')
评论
job
phone
this.job ?? job
this.phone ?? phone