在Javascript中无法通过this访问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'});
在我的订阅者方法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
变量将全局可用。
相关文章:
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- 为什么我不能在 ajax 成功中访问 $(this)
- 在接受功能上访问燃料UX标语牌中的“this”
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- 在jQuery中,我如何从$.ajax回调函数访问$(this)
- TypeScript:在对象文字字段中的访问器中访问外部“this”
- JavaScript 访问函数构造函数中的“this”
- React Native can'无法在render()方法之外访问this.ops
- 通过函数传递“this”时,我是否可以无法访问“this”的属性
- 如何使用“self = this”访问类属性
- 使用“this”访问对象的值
- arguments属性可以由this访问.some_function.arguments?实际上我无法解释
- 使用let初始化的函数在被this访问时不被替换
- 隐藏匿名JavaScript函数中的变量,但使用“this”访问它们
- 如何使用$(this)访问调用Javascript函数的按钮的id
- 在Javascript中无法通过this访问const变量
- 如何在jQuery中使用$(this)访问子元素?
- 无法使用“this”访问对象.“this”指向“窗口”对象
- 使用jQuery的$(this)访问内部文本
- 使用this访问对象内的对象名称