1. this指向汇总
this指向:指向其调用者
- 简单函数
function f(){
console.log(this) //window
};
f();
//因为代码不是运行在严格模式下,this又必须是一个对象,所以他的默认值为全局对象window
//严格模式下为undefined
- 内置函数 this ==== window
setTimeout(f,1000); //window
- 回调函数 —— 简单的理解:一个函数被作为参数传递给另一个函数 this ==== window
function test(v){
console.log(v)
};
//console.log(test); //整个函数
//console.log(test('hello')); //调用后的结果
function f2(callback,v){
callback(v)
};
f2(test,'hello');
//另一种写法
f2(function(v){console.log(v)},'hello'); //匿名函数
//f2(function(v){console.log(this)},'hello'); this ==== window
var arr = [1,2,3,4,5].filter(function(item,index){
console.log(this)
})
- 数组 this的指向调用者
function f3(){
console.log(this);
};
var arr = [f3,4,5,6];
arr[0](); //this ==== arr
var f = arr[0]; //数组赋值处理后 this指向发生了变化
f(); //this ==== Window
- 对象 obj对象中的方法this === obj
function f3(){
console.log(this);
};
var obj = {};
obj.id = 123;
obj.init = function(){
console.log(this) //调用者obj this === obj
};
obj.init()
obj.action = f3; //对象中添加了一个方法 方法赋值f3()
obj.action(); 调用者obj this === obj
- 字面量
var obj2 = {
id:1,
abc:f3
};
obj2.abc(); // this === obj2
- 构造函数
function Fun(name,age) {
this.name = name;
this.age = age;
this.action = function(){
console.log(this)
}
};
var fun2 = new Fun('abc',18);
fun2.action(); //this 指向的是新创建的对象实例, 而不是构造函数本身
2.如何改变this指向
apply() call() bind()
格式:函数名.call/apply/bind(重新指定的this对象,函数参数,函数参数)
可以将原函数中this的指向修改为新的对象
var a = 10;
function f5(x1,x2){
return this.a + " " +x1 +" "+ x2
};
var obj5 = {
a:100,
action:f5
};
var obj6 ={
a:9999
}
obj5.action(1,2); //100 1 2
console.log(obj5.action.call(this,1,2)) //10 1 2 改变作用域
console.log(obj5.action.apply(window,[1,2])) //10 1 2
//obj5.action对象的成员放到window对象上,这样f5的指向就是window
console.log(obj5.action.apply(obj6,[1,2])) //9999 1 2
//bind() 绑定this 也是改变作用域 绑定后不能改变this指向
var a = 10;
function f5(x1,x2){
return this.a + " " +x1 +" "+ x2
};
var obj5 = {
a:100,
action:f5
};
var obj6 ={
a:9999
}
var a8 = f5.bind(obj5,1,2);
a8(); //100 1 2
console.log(a8.call(obj6,1,2))