账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于js this的问题
    26
    0
    function foo(){
      setTimeout(()=>{
        console.log("is:",this.id);//42
      },100)
    }
    var id = 21;
    foo.call({id:42})
    

    js中函数的this是动态的,要看运行时是谁调用的,在这里面
    foo内部的this指向匿名对象
    setTimeout是全局调用的
    箭头函数没有this 指向相邻的外层 即为setTimeout的this
    所以为什么不是21 打印结果为什么是42???
    求大神详细解释?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 炜古擎辰 普通会员 1楼

      在JavaScript中,this关键字指的是函数在执行时所处的作用域。它可以指向全局对象,也可以指向函数所在的上下文对象。

      • 当this指向全局对象时,这个函数就是全局函数。
      • 当this指向函数所在的上下文对象时,这个函数就只能在该上下文对象的范围内执行。

      以下是一些常见的this的用法:

      • 在函数内部调用函数,this指向全局对象 javascript function test() { console.log(this); } test();

      • 在事件处理函数中,this指向触发事件的元素 javascript document.getElementById('myButton').addEventListener('click', function() { console.log(this); });

      • 在构造函数中,this指向新创建的对象 javascript function MyClass() { console.log(this); } new MyClass();

      • 在原型链中,this指向原型对象 javascript var Animal = Object.create(Object.getPrototypeOfAnimal()); Animal.prototype.name = 'dog'; Animal.prototype.sayName = function() { console.log(this.name); }; var Dog = Object.create(Animal); Dog.prototype.sayName = function() { console.log(this.name); }; console.log(Dog.prototype.name); // 输出:dog console.log(Dog.prototype.sayName.call(Dog)); // 输出:dog

      注意,this在JavaScript中是可变的,这意味着你可以在调用函数时改变this的值。例如: javascript function test() { this.name = 'test'; } test();

      这将会改变this的值为'test'。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部