在Javascript中无法通过this访问const变量

Unable to access const variables through this in Javascript

本文关键字:this 访问 const 变量 Javascript      更新时间:2023-09-26

我正在探索ES6的const关键字,一切都为我工作,除了一些范围问题,我无法理解。

有一个简单的js文件

    const reducer = (state = 0,action) => {
    switch(action.type) {
        case 'Increment' : 
            return state+=1;
        case 'Decrement' :
            return state-=1;
        default :
            return state;       
    };
}
const {createStore} = Redux;
const store = createStore(reducer);
const getstate = () => {
    return store.getState();
}
// var getstate = () => {
//  return store.getState();
//} it is working
store.subscribe(() => {
    console.log(this);
    console.log(this.getstate());
    //console.log(getstate());   it is working
})
store.dispatch({type:'Increment'});

在我的订阅者方法this。当我将const getstate更改为var getstate时,getstate返回myjs.js:20 Uncaught TypeError: this.getstate is not a function,它开始工作。同样,当我将this.getstate更改为getstate时,它也在工作

从浏览器控制台我可以访问getstate,但我无法访问this.getstate。这是在窗口作用域,但为什么它不能访问const变量?

您遇到的问题是,当您使用const创建变量时,这是无法通过window对象访问的(尽管变量是全局的)。我建议避免创建全局功能,并将代码组织为IIFE模块模式

如果你想保持你的方式,你能做的最好的是添加语义到你的代码一个附加变量直接到window对象。这样做,你的意图将是明确的:

window.getstate = () => {
    return store.getState();
}

当你调用this.getState时,它会从下往上查找getState变量

global context which is window object -- TOP -- find getState in window object, if not return undefined
  ---> local context which is your current file -- find getState in this file, if not go up
    ----> current method which is () => { 
        this.getState() <-- find getState in this function, if not go up 
      } BOTTOM

根据这个文档:

常量是块作用域,很像使用let语句定义的变量。

这意味着当您定义const getState时,它仅在当前文件中可用。

当你定义var getState时,它不是块作用域,getState变量将全局可用。