this指向

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实例本身

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值