Home > Web Front-end > JS Tutorial > body text

How to change the value pointed to by this in a function in JavaScript?

伊谢尔伦
Release: 2017-07-20 13:34:06
Original
1526 people have browsed it

fun.apply(context,[argsArray])

Call fun immediately, and at the same time point the original this of the fun function to the new context object passed in, implementing the same method in different reused on the object.

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]' ;
}  //验证是否是数组
Copy after login

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
Copy after login

Use bind in the event handling 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
  }
}
Copy after login

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


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

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
    }
  }
}
Copy after login

Generally, this of setTimeout() points to 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" ;
Copy after login

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

The above is the detailed content of How to change the value pointed to by this in a function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template