本文主要介绍JavaScript中this指向的问题。
1.指向window
全局作用域以及函数作用域中的this,都指向window对象。
function func() {
console.log('函数作用域下的this。window调用了函数,故指向调用对象');
console.log(this);
}
window.func();
console.log('全局作用域下的this');
console.log(this);
注意:在严格模式下,函数中的this是undefined.
'use strict';
function a() {
console.log(this);
}
a();
2.指向绑定的元素
事件绑定时的this指向绑定的元素。
var btn = document.querySelector('button');
btn.onclick = function() {
console.log('事件绑定时的this指向');
console.log(this);
}
3.指向对象
对象中的this指向该对象本身
var person = {
name: 'zs',
age: 23,
show: function() {
console.log('对象中的this指向该对象');
console.log(this);
}
}
person.show();
4.指向构造函数的实例化对象
构造函数中的this指向由该函数实例化出来的对象
function Person(name, age) {
this.name = name;
this.age = age;
this.say = function() {
console.log('构造函数中的this指向实例化对象');
console.log(this);
return '姓名:' + this.name;
}
}
console.log(new Person('ls', 24).say());