JavaScript之this的指向

今天学了下在JavaScript中this 的简单用法,总结了一下。

在全局环境中的this指向

console.log(this);		//window

在全局环境中直接打印出this是指向window对象的。

在函数内的this指向

function myFunction(){
            console.log(this)
        }
 myFunction();			//window

因为此函数在直接在window环境中定义,所以它的this指向window。
该函数的调用写法也可以这么写:

window.myFunction();

在对象方法中的this指向

var person = {
   ullName: function(){
       console.log(this)
    }
 }
 person.fullName();//person对象

因为fullName方法是定义在person对象内的,所以它的this指向person对象。

在事件句柄函数中的this指向

<button id="btn">this</button>

document.getElementById('btn').onclick = function(){
    console.log(this);			//调用该方法的dom节点
}

事件句柄里面的this指向的是调用事件函数的dom节点

apply bind call 改变this指向

		//call apply bind
        var person1 = {
            fullName: function(){
                console.log(this.firstName + '' + this.lastName);
            }
        }
        var person2 = {
            firstName: '王',
            lastName: '宇豪'
        }

        //都输出王宇豪
        person1.fullName.call(person2);
        person1.fullName.apply(person2);
        person1.fullName.bind(person2)();

这三个方法可以将一个对象的方法绑定到另一个对象中执行,也就是person2调用了person1的方法,所以this指向也改变到了person2.

严格模式里面的this指向

//严格模式下函数没有绑定到this上,所以这时候this是undefined
    "use strict";
    function fff(){
        console.log(this);
    }
    fff();//undefined

在严格模式下,全局环境中定义的函数没有绑定this,所以是undefined。

注意: 除了此种情况,其他以上的其他情况严格模式都与非严格模式相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值