A
The method of binding function in an object, called this object:
Example:
var xiaoming = {
name: '小明',
birth: 1990,
age: function () { var y = new Date().getFullYear(); return y - this.birth; } }; xiaoming.age; // function xiaoming.age() xiaoming.age(); // 今年调用是25,明年调用就变成26了
其中在一个方法内部,this
是一个特殊变量,它始终指向当前对象,也就是xiaoming
这个变量。
若将函数写在对象外部,单独调用函数则会返回NaN,因为函数相当于全局函数,this指向了window
例:
function getAge() { var y = new Date().getFullYear(); return y - this.birth; } var xiaoming = { name: '小明', birth: 1990, age: getAge }; xiaoming.age(); // 25, 正常结果 getAge(); // NaN
B apply
(1)改变this指向
要指定函数的this
指向哪个对象,可以用函数本身的apply
方法,它接收两个参数,第一个参数就是需要绑定的this
变量,第二个参数是Array
,表示函数本身的参数。
用apply
修复getAge()
调用:
例:
function getAge() { var y = new Date().getFullYear(); return y - this.birth; } var xiaoming = { name: '小明', birth: 1990, age: getAge }; xiaoming.age(); // 25 getAge.apply(xiaoming, []); // 25, this指向xiaoming, 参数为空
And other apply()
similar methods is call()
the only difference is:
-
-
apply()
The parameter packaged intoArray
reinjecting; -
call()
The parameters passed in order.
-
Such as calling Math.max(3, 5, 4)
, respectively apply()
, and call()
to achieve the following:
Math.max.apply(null, [3, 5, 4]); // 5 Math.max.call(null, 3, 5, 4); // 5
Ordinary function call, we usually this
bind to null
.
Behavior (2) dynamic change function
Example:
Want to run the code to call a total of how many timesparseInt()?
Problem-solving ideas: he re-wrote a js function to replace the default parseInt () function
COUNT = 0 var;
var = oldParseInt the parseInt; // save the primitive
window.parseInt = function () {
COUNT + =. 1;
return oldParseInt.apply (null, arguments); // call the original function
};
excerpt from the teacher Liaoxue Feng Official website