Home > database >  Need of a call(), apply() and bind() method
Need of a call(), apply() and bind() method

Time:11-20

I have read lot of theory regarding call(), apply() and bind().

I am not able to understand if we can call method directly why we need call() , apply() or bind()?

Can somebody explain in laymen terms and little in terms of JavaScript?

CodePudding user response:

That's the flexibility offered by Javascript, an object and it's method don't have to be coupled with each other.

Given following object 'a' with a member method 'play'

var a = { play: function (content) { console.log("what is this:", this, content)} }

Use

a.play('Hello')

Is equivalent to

a.play.call(a, 'Hello')

As for your question why need the second way 'call'. Because 'call' gives you a way to call something else instead of 'this', which is 'a' in the example above, so you can do:

a.play.call(document, 'Hello')

About 'apply', it's just another version of 'call', which needs you to pass arguments as an array instead of comma separated parameters. To use apply, you do:

a.play.apply(a, ['Hello'])

As for 'bind', it is to link a function with a 'this' object at first, then get a returned callable object, which you can either call with the rest arguments directly, or pass it into anything else to be called later.

A typical 'bind' use case is React component's event handler. To define an event handler to be passed into a component. You need to use 'bind' in a React class component like this:

handleClick = this.handleClick.bind(this)

Then, in render function:

<Button onClick={this.handleClick} />

Check https://reactjs.org/docs/handling-events.html for the full information.

  • Related