this指向的形式:
1.一般函数,this指向全局对象window;
2.严格模式下,如果this没有被执行环境定义,undefined;
3.对象的方法里调用,this指向调用该方法的对象;
4.构造函数里的this,指向创建的实例
5.apply,call,bind调用模式,this指向第一个参数
6.箭头函数,在声明时绑定this,不取决于调用位置,指向它的上一层
this各种形式里指向
1.全局作用域或普通函数 this指向全局对象window
直接打印
console.log(this)
声明函数
function bar() {
console.log(this)
}
bar() //this:window
严格模式
function bar() {
"use strict"
consloe.log(this)
}
bar()//this:undifined
声明函数赋给变量
var bar = function() {
console.log(this)
}
bar()
函数自执行
(function() {
console.log(this)
})();
2.方法调用 this指向调用该方法的对象
对象方法调用
var person = {
run: function() {
console.log(this)
}
}
person.run()
//Object { run: run()}
事件绑定
var btn = document.querySelector(".button")
btn.onclick = function() {
console.log(this)
}
//<button class="button">
事件监听
var btn = document.querySelector(".button")
btn.addEventListener('click', function() {
console.log(this)
})
//<button class="button">
3.在构造函数或构造函数原型对象中this指向创建的实例
不使用new
function Person(name) {
console.log(this)
this.name = name;
}
Person('az')
//this:window
new
function Person(name) {
this.name = name
console.log(this)
self = this
}
var people = new Person('az')
console.log(self === people)
//Object { name: "az" }
//new改变了this指向, 将this由window指向Person的实例对象people
4.当构造函数中有return
function fn() {
this.user = '布洛特亨德尔';
return {};
}
var a = new fn;
console.log(a.user)
//undefined
function fn()
{
this.user = '布洛特亨德尔';
return function(){};
}
var a = new fn;
console.log(a.user); //undefined
//返回fn
function fn() {
this.user = '布洛特亨德尔';
return 1;
}
var a = new fn;
console.log(a.user);//布洛特亨德尔
5.箭头函数中指向外层作用域的 this
var obj = {
foo() {
console.log(this);
},
bar: () => {
console.log(this);
}
}
obj.foo()
obj.bar()
//Object { foo: foo(),bar: bar()}
//window