this的指向
this指向的对象不是固定不变的,取决于上下文环境,一般
认为this指向使用它时所在的对象
1.this指向全局对象
var a=1;
console.log(this);
console.log(this.a)
2.独立函数中,在严格模式下,this 是未定义的(undefined)。
function f2() {
console.log(this);//window
}
function f() {
"use strict"; // 这里是严格模式
console.log(this);//undefined
}
f();
f2();
3.作为对象中的方法调用,this指向对象本身
//方法中的this
var isObject = {
a: 'inner object',
innerFunction: function() {
return this.a;
}
};
console.log('方法里的this指向:', isObject.innerFunction());//inner object
this指向的是使用它时所在的对象
//函数中使用this test1
var variable = 'window';
function outerFunction() {
var variable = 'test';
return this.variable;
}
console.log('函数中this指向:', outerFunction());//window
console.log('函数中this指向:', window.outerFunction());//window
//函数中使用this test2
var variable = 'window';
var isObject = {
variable: 'test',
innerFunction: function outerFunction() {
return this.variable;
},
}
console.log('函数中this指向:',isObject. innerFunction()); //test
注意:箭头函数内部并没有绑定this的机制,所以this的指向是固定的,即指向当前定义时所在的对象
//箭头函数
var variable = 'window';
var isObject = {
variable: 'test',
innerFunction: () => {
return this.variable;
}
}
console.log('函数中this指向:',isObject. innerFunction()); //window
4.构造函数中的this与被创建的新对象绑定
//构造函数
function Person0(age, name) {
this.age = age;
this.name = name
console.log(this) // 此处 this 指向 Person 的实例对象 p
}
var p = new Person0(18, 'zs')
console.log(p.age)
5.在事件中,this 表示接收事件的元素
<button onclick="this.style.display='none'">
点我我就消失
</button>
6.通过call,apply,bind调用函数改变this指向,指向调用者
call方法可以添加多个参数
apply也可以有多个参数,但是第二个参数必须是一个数组
注意如果call和apply的第一个参数写的是null,那么this指向的是window对象
bind也可以有多个参数,并且参数可以执行的时候再次添加,但是要注意的是,参数是按照形参的顺序进行的
bind改变指向后不会立即执行,相当于一个改变后的函数,可随时调用。而call,apply是改变后立即执行
// call() apply() bind()
var obj={
a:'1',
b:'2'
};
function add(param){
this.c=param;
console.log(this.c);
console.log(this);
}
add('3');
add.call(obj,'3');
add.apply(obj,['3' ]);
add.bind(obj,'3')()//转为立即执行
7.定时器函数this指向全局对象window,可通过bind等改变this指向,或改为箭头函数
function Person() {
this.age = 0;
setTimeout(function() {
console.log(this);
}, 1000);
}
var p = new Person();//1秒后返回 window 对象
// //通过bind绑定
function Person2() {
this.age = 0;
setTimeout((function() {
console.log(this);
}).bind(this), 3000);
}
var p = new Person2();//3秒后返回构造函数新生成的对象 Person{...}
function Person3() {
this.age = 0;
setTimeout(() => {
// 回调里面的 `this` 变量就指向了期望的那个对象了
this.age++;
console.log(this)
}, 3000);
}
var p = new Person3();
例题
//例题一
var x = 3;
var y = 4;
var obj = {
x: 1,
y: 6,
getX: function() {
var x =5;
return function() {
return this.x;
}();
},
getY: function() {
var y =7;
return this.y;
}
}
console.log(obj.getX())//3
console.log(obj.getY())//6
//例题二
var x = 20;
var a = {
x: 15,
fn: function() {
var x = 30;
return function() {
return this.x
}
}
}
console.log(a.fn()); //function() {return this.x}
console.log((a.fn())());//20
console.log(a.fn()());//20
console.log(a.fn().call(this));//20
console.log(a.fn().call(a));//15
注意:立即执行函数指向window
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。