改变函数内的this指向 js提供了三种方法: call() 、apply()、 bind()
1、call方法
call方法可以调用函数,还可以改变函数内的this指向。
例如:
var o = {
name: 'andy'
}
function fn(a,b){
console.log(this);
console.log(a+b)
}
fn.call(o, 1, 2);
call()方法的主要作用是实现继承。
例如:
function Father (uname, age, sex){
this.uname = uname;
this.age =age;
this.sex =sex;
}
function Son(uname, age, sex){
//把Father的this 改为 Son的this
Father.call(this, uname, age, sex);
}
var ldh = new Son('刘德华','18','男');
2、apply()方法
apply()方法也是调用函数、第二个可以改变函数内部的this指向,但是它的参数必须是数组(伪数组)。
例如:
var o ={
name:'andy',
}
function fn(arr){
console.log(this);
console.log(arr); //打印的结果是字符串 'pink'
}
fn.apply(o,['pink']);
apply的主要应用:比如说我们可以利用 apply 借助数学内置对象求最大值。
var arr = [1,66,3,99,4];
var max = Math.max.apply(Math,arr);
console.log(max); //9
3、bind()方法
bind()方法不会调用原来的函数 可以改变原来函数内部的this指向。返回的是原函数改变this之后产生的新函数。
例如:
var o ={
name: 'andy'
}
function fn(){
console.log(this);
}
var f = fn.bind(o);
f();