簡體   English   中英

無法通過此方法在Javascript中訪問const變量

[英]Unable to access const variables through this in Javascript

我正在探索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'});

在我的訂戶方法中, myjs.js:20 Uncaught TypeError: this.getstate is not a function返回myjs.js:20 Uncaught TypeError: this.getstate is not a function當我將const getstate更改為var getstateconst getstate myjs.js:20 Uncaught TypeError: this.getstate is not a function ,它開始工作。 此外,當我改變this.getstategetstate ,它也在努力

從瀏覽器控制台中,我可以訪問getstate,但是無法訪問this.getstate。 這是在Window范圍內,但是為什么它無法訪問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塊限制的var getStategetState變量將在全局范圍內可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM