Home >Web Front-end >JS Tutorial >Summary of Function.prototype.apply() and Function.prototype.call()_Basic knowledge

Summary of Function.prototype.apply() and Function.prototype.call()_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:03:311675browse

I always forget the use of these two things and write them down for a record.
Their functions are exactly the same, but the parameters passed in are different

apply

apply accepts two parameters. The first one specifies the pointer to the this object in the function body. The second parameter is a subscripted collection (traversable object). The apply method passes the elements in this collection as parameters to the object. Function called:

var func = function(a, c, c){
  alert([a,b,c]); //[1,2,3]
}
func.apply(null, [1,2,3]);

call

The parameters passed in call are not fixed. The same as apply, the first parameter also represents the this pointer in the function body. Starting from the second parameter, each parameter is passed into the function in turn:

var func = function(a, b, c){
  alert([a,b,c]); //[1,2,3]
}
func.call(null, 1,2,3);

call is a syntactic sugar for aply. If the first parameter is null, this in the function body points to the host object, which is window in the browser.

The purpose of call and apply

1. Change this to point to

That’s the example above

2.Function.prototype.bind

Mock Function.prototype.bind

Function.prototype.bind = function(context){
  var self = this;
  return function(){
    return self.apply(context, arguments);
  }
};

var obj = {
  name: 'cxs'
};

var func = function(){
  alert(this.name); //cxs
}.bind(obj);

fun();

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn