Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

关于es6的箭头函数this指向报错

看了箭头函数的解释,他会将this指向外层的代码,或者指向定义时候的作用域,但是我做实验的时候没有得到正确的数据,求帮忙看看,谢谢

const obj = {
    msg: 'ping',
    ping: () => this.msg
};
//理论上这个返回undefined很正常,因为箭头指向了全局作用域
console.log(obj.ping()); //返回undefined
//但是我这里设置了一个全局作用域下的相同的变量,为什么也返回undefined呢
var msg = 'bang!';
console.log(obj.ping()); //返回undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你应该是在node环境下运行的,node有模块等,在浏览器中试试。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...