class内部function定义的函数this指向undefined

class会默认开启严格模式,严格模式下this的默认指向为undefined 

class Fun {
    constructor() {
        let resolve = function() {
            console.log('this', this)
        };
        resolve();
    }
}

new Fun(); // this undefined

如上代码,在constructor里面用function定义了一个函数,函数打印this,然后直接调用该函数,正常情况该this应该是window,这里this的指向却是undefined。

我搜了相关信息才发现,class会默认开启严格模式,严格模式下this的默认指向为undefined

class相关

 这里使用箭头函数就好了,利用箭头函数this指向上下文的特点

class Fun {
    constructor() {
        let resolve = () => {
            console.log('this', this)
        };
        resolve();
    }
}

new Fun(); // this Fun

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在JavaScript中,构造函数的this指向创建的实例对象。当使用new操作符调用构造函数时,this就指向了新生成的对象。这一点非常重要。举个例子来说明,比如有一个构造函数Person,当使用new操作符创建一个实例对象p时,构造函数中的this指向了这个新生成的实例对象。例如: ```javascript function Person() { this.name = "Tiny Colder"; var age = 22; window.age = 22; } var p = new Person(); console.log(p.name); // "Tiny Colder" console.log(p.age); // undefined console.log(window.age); // 22 ``` 在上面的例子中,构造函数Person中的this指向了新生成的实例对象p,所以通过p访问name属性可以得到正确的值,而通过p访问age属性则得到undefined,因为age是在构造函数中用var声明的局部变量,并没有添加到this上。而window.age是在构造函数中用window对象添加的全局变量,所以可以通过window对象访问到。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [js构造函数中this的指向问题?](https://blog.csdn.net/m0_53892583/article/details/116525105)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [JavaScript中this的指向 详解](https://blog.csdn.net/qq_52320207/article/details/116762893)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值