js中this的指向

文章详细阐述了JavaScript中this关键字在不同场景下的指向规则,包括普通函数、对象方法、构造函数、定时器以及闭包中的行为。在普通函数中,this指向全局对象(在浏览器中是window),在对象方法里,this指向方法所属的对象,构造函数中的this指向新创建的实例,定时器里的this同样指向全局对象,而在闭包中,this的指向取决于其定义时的环境。
摘要由CSDN通过智能技术生成

原则谁调用,就指向谁

 1.普通函数

function add(){
    console.log(this)
}
add()

this指向window

2.对象.函数()

     var x = 100;
        const obj = {
            x: 19,
            y: 20,
            add: function () {
                return this.x + this.y;
            }
        }
        const sum=obj.add();
        console.log(sum);//39

this指向方法所属对象

3.构造函数中的this

        function Star(name,age){
            this.name=name;
            this.age=age;
        }
        Star.prototype.sing=function(){
            console.log(this)
        }
     
        let star=new Star('tom',18)
        star.sing();

this指向实例对象 

4.定时器

setTimeout(
  function(){
    console.log(this)
  },1000
)

this指向window

5.闭包中的this对象

<1 >this指向window对象

var name = "window对象";
        var obj = {
            name: "Object对象",
            getName: function () {
                return function () {
                    return this.name;
                }
            }
        }

        console.log("name=", obj.getName()());

name=window对象

<2>this指向外部函数的执行环境

      var name = "window对象";
      var obj = {
          name: "Object对象",
          getName: function () {
              var that = this;
              return function () {
                  return that.name;
              }
          }
      }

    console.log("name=", obj.getName()());

name= Object对象

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值