1、常见的情形中this的指向
函数中的this指向分以下几类情况:
- 普通函数中的this
/**
* 普通函数中的this: window
*/
function testQuery(){
console.dir(this);
}
- 定时器方法中的this
/**
* 普通函数中的this: window
*/
setInterval(function (){
console.dir(this);
}, 1000);
- 构造函数中的this
/**
* 构造函数中的this: 实例对象
*/
function Person(){
console.dir(this);
}
var per = new Person();
- 原型对象方法中的this
/**
* 原型对象方法中的this:实例对象
*/
Person.prototype.eat = function (){
console.dir(this);
};
per.eat();
- 普通函数中的this
/**
* 对象.方法中的this:实例对象
*/
2、如何改变this的指向
为了使用某种特定环境的 this 引用, JavaScript 为我们专门提供了一些函数方法用来帮我们更优雅的处理函数内部 this 指向问题,包括 call、apply、bind 三个函数。
- call
基本语法:fun.call(thisArg[, arg1[, arg2[, …]]])
thisArg –The value to use as this when calling func. 调用方法时this实际指向
arg1, arg2, ...argN – Arguments for the function. 调用方法的入参
- apply
基本语法:fun.apply(thisArg, [argsArray])
thisArg –The value to use as this when calling func. 调用方法时this实际指向
argsArray – An array-like object, specifying the arguments with which func should be called. 调用方法的入参
例:
function Person(age){
this.age = age;
}
Person.prototype.sayHi = function (x, y){
console.log((x + y) + " ==== " + this.age);
};
function Student(age){
this.age = age;
}
var person = new Person(10);
var student = new Student(20);
// apply和call,第一个参数代表this的实际指向,第二个参数代表调用方法时的实参
// 不同之处:apply的第二个参数是数组,call的第二个参数是可变参数列表
person.sayHi.apply(student, [10, 60]);
person.sayHi.call(student, 10, 60);
- bind
基本语法:bind(thisArg[, arg1[, arg2[, …]]])
对于一个给定的函数,bind会创建一个和原始函数一样的函数,这个新创建的函数的this对象会绑定到bind(thisArg, args)的第一个参数thisArg上,且这个函数具有args这些参数。
返回值是一个函数。
/**
* bind 赋值一份函数,并绑定到指定的对象,可以改变this的指向
*
* 函数名.bind(对象, 参数1, 参数2, ...)
* 返回的是复制后的函数
*
*/
function Person(age){
this.age = age;
}
Person.prototype.sayHi = function (){
console.log("sayHi...");
};
function Student(age){
this.age = age;
}
var person = new Person(10);
var student = new Student(20);
/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg The object to be used as the this object.
* @param args Arguments to bind to the parameters of the function.
*/
// 复制一份
var ff = person.sayHi.bind(student);
ff();