DEV Community

Kaziu
Kaziu

Posted on • Edited on

😎 imposter of "this". apply(), call(), bind()

💎 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"
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()

Enter fullscreen mode Exit fullscreen mode

basic pattern of call() is like that, actually apply() as well

someFunction.call(imposter of "this");
Enter fullscreen mode Exit fullscreen mode

🙄 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])
Enter fullscreen mode Exit fullscreen mode

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)