this指向
单独直接使用
this指向全局(Global)对象。在浏览器中,window 就是该全局对象为window: [object Window]
var x = this;
console.log(this);//Window {window: Window, self: Window, document: document, name: '', location: Location, …}
var y = 'hello';
console.log(this.y);//hello
全局函数中(默认)
this 表示函数所属的对象。浏览器中,全局函数所属对象是全局对象 window: [object Window]
var x = 5
function fn() {
console.log(this);//Window {window: Window, self: Window, document: document, name: '', location: Location, …}
console.log(this.x);//5
}
fn()
全局函数中(严格模式)
严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。
"use strict";
function myFunction() {
return this;
}
console.log(myFunction());//undefined
对象方法中
在对象方法中, this 指向调用它所在方法的对象。
var person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
},
myFunction: function () {
return this;
}
};
console.log(person.fullName());//John Doe
console.log(person.myFunction());//{firstName: 'John', lastName: 'Doe', fullName: ƒ, myFunction: ƒ}
箭头函数中
this指向window对象
var name = "lily"
var person = {
name:"mimi",
getName1: () => {
return this.name
},
getName2: function () {
return this.name
}
}
console.log(person.getName1());//lily
console.log(person.getName2());//mimi
事件中
this 表示接收事件的元素
<h1 onclick="changetext(this)">点击文本!</h1>
function changetext(el) {
console.log(el);//<h1 οnclick="changetext(this)">点击文本!</h1>
}
显式函数绑定(call()、apply()、bind()指定this指向)
var person1 = {
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName: "John",
lastName: "Doe",
}
console.log(person1.fullName.call(person2));// 返回 "John Doe"
vue实例本身的属性和方法中(非箭头函数中)
this指向vue实例本身