π Imposter of 'this'
At first show you this sample of call(), it's ok if you don't get it so far
class MyHouse {
constructor() {
this.ownerName = 'Kaziu'
}
enter() {
console.log(`${this.ownerName} enter house`)
}
}
class Thief {
constructor() {
this.ownerName = 'Thief'
}
}
const myHouse = new MyHouse()
myHouse.enter()
// => "Kaziu enter house"
const thief = new Thief()
// β Thief class doesn't have enter method, but it can invoke by call
myHouse.enter.call(thief)
// => "Thief enter house"
Why gets like this result? at first this in enter() shows MyHouse instance.
class MyHouse {
constructor() {
this.ownerName = 'Kaziu'
}
enter() {
console.log(this)
// β "MyHouse {ownerName: 'Kaziu'}"
}
}
const myHouse = new MyHouse()
myHouse.enter()
but when executes call(), we can change this this
class MyHouse {
constructor() {
this.ownerName = 'Kaziu'
}
enter() {
console.log(this)
// β "Thief {ownerName: 'Thief'}"
// π³ now instance of Thief !!!!!!!!!!!!!!!!!!!!!
}
}
class Thief {
constructor() {
this.ownerName = 'Thief'
}
}
const thief = new Thief()
myHouse.enter.call(thief) // β¬
here invoke call()
basic pattern of call() is like that, actually apply() as well
someFunction.call(imposter of "this");
π So what is difference between call() and apply() ???
difference between call and apply is apply can takes array in second argument
class MyHouse {
constructor() {
this.ownerName = 'Kaziu'
}
// β add arguments date and age
enter(date, age) {
console.log(this) // Thief {ownerName: 'Thief'}
console.log(date) // 2021-8-21
console.log(age) // 76
}
}
class Thief {
constructor() {
this.ownerName = 'Thief'
}
}
const thief = new Thief()
myHouse.enter.call(thief, '2021-8-21', 76)
// β In case of apply, need to add array in second argument
myHouse.enter.apply(thief, ['2021-8-21', 76])
This is simple sample of call() and apply(), They can control of this, it's keyword
bind()
There is similar method bind in javascript. Between call, apply and bind is that bind doesn't invoke function immediately.
Top comments (0)