前端学习辑录(2):JS中this指向的问题


this指向的不同场景:

一、普通函数调用

普通函数中的this是谁?===>window

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

严格模式下的普通函数中的this?

   "use strict";//严格模式
   function f1() {
     console.log(this);
   }
   f1();//undefined
   window.f1(); //==>window
   //严格模式下调用函数,它会认为函数就是方法
   //方法通过对象调用,你的对象没写

二、定时器函数

   window.setInterval(function () {
     console.log(this); //window
   },1000);

三、构造函数调用

 	function Person(){
        console.log(this);//Person==>实例对象
    }
    var per=new Person();
    console.log(per);

四、对象方法调用

 	function Person(){
        console.log(this);//Person==>实例对象
        this.sayHi=function () {
            console.log(this);//Person==>当前实例对象
        };
    }
    var per=new Person();
    console.log(per);
    per.sayHi();

五、原型对象调用

 function Person(){
        console.log(this);//Person==>实例对象
        this.sayHi=function () {
            console.log(this);//Person==>实例对象
        };
    }
    Person.prototype.eat=function () {
        console.log(this);//Person==>实例对象
    };
    var per=new Person();
    console.log(per);
    per.sayHi();
    per.eat();

总结

本章总结了js中经常见到的this指向问题,汇总如下表:

调用方式非严格模式备注事项
普通函数window严格模式下是undefined
定时器函数window
构造函数实例对象
对象方法该方法所属对象临近的对象
原型对象方法实例对象
事件绑定方法绑定事件对象

以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值