Home  >  Article  >  Web Front-end  >  apply/call/bind and this in JavaScript

apply/call/bind and this in JavaScript

高洛峰
高洛峰Original
2017-02-28 14:43:351023browse

The connection between apply/call/bind is that they can all be used to change the value pointed to by this in the function, and the first parameter is the value of this to be pointed to, and the second parameter of apply (or bind and call's variable parameters) are the parameters to be passed in. This has to mention the point of this of the function in javascript. Let's briefly discuss

fun.apply(context,[argsArray])

Call fun immediately, and at the same time point the original this of the fun function to the incoming new The context object implements the same method and reuses it on different objects.

context: the object passed in, replacing the original this of the fun function;

argsArray: an array or array-like object, in which the array parameters will be expanded and passed to fun as separate actual parameters For functions, you need to pay attention to the order of parameters.

fun.call(context,[arg1],[arg2],[…])

Same as apply, except that the parameter list is different. The parameters of call need to be separated. An incoming. If you don't know the number of parameters, use apply.

Use:

Math.max() //Only receive individual parameters, you can use the max method on the array through the following method:
Math.max.apply(null, array); //Will expand the array array parameters into separate parameters and then pass them in
Array.prototype.push.apply(arr1,arr2); //Split one array and push it into another array; no need to apply Then the subsequent array parameters will be pushed in as an element.
Array.prototype.slice.call(arguments); //Use the slice method on the class element group object

##

function isArray(obj){
  return Object.prototype.toString.call(obj) === '[object Array]' ;
}  //验证是否是数组


fun.bind(context,[arg1],[arg2],[…])

Make the context executed by the fun method never change.

arg1: Argument list to be passed to the new function

Returns a function for subsequent calls. Its function body is the same as the original function fun, but the this of the new function points to the newly passed in context object. . The new function will have the initial parameters arg1/arg2... specified by the bind method. The actual parameters when subsequently calling the new function will be arranged behind the existing parameters.

//原来的函数有4个参数
var displayArgs = function (val1, val2, val3, val4) {
  console.log(val1 + " " + val2 + " " + val3 + " " + val4);
}
var emptyObject = {};
// 生成新函数时bind方法指定了2个参数,则新函数会带着这个两个实参
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");
// 调用时传入另2个参数,要在bind方法传入的2个实参后面
displayArgs2("b", "c");
// Output: 12 a b c

Use bind in the event handler function:

var obj = {
  arg1 : 1,
  attach: function(){
    //var self = this; 普通传入this 的方法
    $('xxx').on('click',function (event) {
      console.log(this.arg1);//若不绑定this,回调函数中的this常指目标元素
     }.bind(this));  //使用bind方法绑定this
  }
}


Use the bind() method to rewrite the slice() method:

var _Slice = Array.prototype.slice;
var slice = Function.prototype.call.bind(_Slice);
slice(…);

bind() is compatible with Ie5~ie8 processing

if (!Function.prototype.bind) {
  Function.prototype.bind = function(context) {
    var self = this, // 调用bind方法的目标函数
    args = arguments;
    return function() {
      self.apply(context, Array.prototype.slice.call(args, 1));//参数个数不确定时用apply
    }
  }
}

Generally, this of setTimeout() points to the window or global object. When using a class method and you need this to point to a class instance, you can use bind() to bind this to the calling object instead of passing in self.

this

#This object is bound based on the execution environment of the function when the function is running: in the global function, this is equal to window, and when the function is treated as When a method of an object is called, this is equal to that object.

Judgment method: this has nothing to do with where it is defined. When the function is running, if there is a . operator, this refers to the object before .; if not, this refers to the window. If the new keyword is called, it refers to a new object. When there is apply/call/bind, it refers to the first parameter.

/*例1*/
function foo() {
  console.log( this.a );
} 
var obj2 = {
  a: 42,
  foo: foo
};
var obj1 = {
  a: 2,
  obj2: obj2
};
obj1.obj2.foo(); // 42;当foo函数被调用时,其本身是归obj2所拥有
/*例2*/
function foo() {
  console.log( this.a );
} 
var obj = {
  a: 2,
  foo: foo
};
var bar = obj.foo;   // bar引用foo函数本身
var a = "global";   // 全局对象的属性
bar();        // "global" ;

In an HTML DOM event handler, this always points to the DOM node to which the handler is bound.

For more articles related to apply/call/bind and this in JavaScript, please pay attention to the PHP Chinese website!



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