对象文字属性值简写与`this`不兼容 [英] Object Literal Property Value Shorthand incompatible with `this`

查看:34
本文介绍了对象文字属性值简写与`this`不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中可以执行以下操作:

In JavaScript it is possible to do:

var a = {this: this}

但是使用ES6属性速记,我会收到SyntaxError:

but with ES6 property shorthand I get SyntaxError:

var b = {this}; // SyntaxError: this is a reserved identifier

这不是一个真正的用例,但我只是想知道这两者之间有什么区别.我认为它应该做同样的事情(创建一个新对象或抛出一个错误).

This is not a real use case but I am just wondering what is the difference between these two. I thought it should do the same (either create a new object or throw an error).

更新:

我在Firefox 42.0中运行此示例.但是它可以在babel-node中工作(它创建对象 {this:{}} 时没有错误).那么正确的行为是什么?

I run this example in Firefox 42.0. However it works in babel-node (it creates object { this: {} } without error). So what's the correct behavior?

推荐答案

该速记属性初始值设定项的语法规定,所用的单个术语必须为标识符.由于 this 是保留字,因此它不是标识符,因此会出现语法错误.

The grammar for that shorthand property initializer clause stipulates that the single term used must be an Identifier. Because this is a reserved word, it isn't an identifier, so you get a syntax error.

该规范的相关部分是第12.2.6节.

这篇关于对象文字属性值简写与`this`不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆