so I have created two objects: person and Tim.
I would like to bind logInfo function to the Tim but when I call this with binding, it keeps giving me:
Here is the code:
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?
Do I seem to miss something? Thank you in advance!
In logInfo function, remove this for job and phone as they are being accepted via arguments and are not property of Tim object. this always refers to current object and this.something points to property of the object .
Refer updated code
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')