markdown JS:Bind,Call,Apply

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown JS:Bind,Call,Apply相关的知识,希望对你有一定的参考价值。

## Function calls: call, apply and bind
All of these three methods are used to attach this into function and the difference is in the function invocation.

**.call()** invokes the function immediately and requires you to pass in arguments as a list (one by one).

**.apply()** invokes the function immediately and allows you to pass in arguments as an array.

**.call()** and .apply() are mostly equivalent and are used to borrow a method from an object. Choosing which one to use depends on which one is easier to pass the arguments in. Just decide whether it’s easier to pass in an array or a comma separated list of arguments.

### Quick tip: Apply for Array — Call for Comma.
```sh
const Snow = {surename: 'Snow'}

const char = {
  surename: 'Stark',
  knows: function(arg, name) {
    console.log(`You know ${arg}, ${name} ${this.surename}`);
  }
}

char.knows('something', 'Bran');              // You know something, Bran Stark
char.knows.call(Snow, 'nothing', 'Jon');      // You know nothing, Jon Snow
char.knows.apply(Snow, ['nothing', 'Jon']);   // You know nothing, Jon Snow
```

以上是关于markdown JS:Bind,Call,Apply的主要内容,如果未能解决你的问题,请参考以下文章

JS中的call,apply和bind及记忆方式

js中call,apply,bind的实现原理()

js中call,apply,bind的实现原理()

JS call,apply, bind区别

js中的call apply bind

原生JS实现call,apply,bind函数