javascript - 计算属性名称上的 JS 属性访问器在表达式与赋值中的行为不同

标签 javascript ecmascript-6 syntax-error

如下图,案例1、案例2、案例3access a property包含 computed property name 的对象的.

情况 1 在函数参数中创建这样的对象,而情况 2 在赋值中创建这样的对象。情况 3 在语句中创建这样一个对象。

为什么情况 3 会产生语法错误?

案例1

$ node -e "var other = 'b'; console.log({a: 1, [other]: 2}[other]);"
2

案例2

$ node -e "var other = 'b'; var obj = {a: 1, [other]: 2}[other]; console.log(obj);"
2

案例3

$ node -e "var other = 'b'; {a: 1, [other]: 2}[other];"
[eval]:1
var other = 'b'; {a: 1, [other]: 2}[other];
                               ^

SyntaxError: Unexpected token :
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:570:32)
    at evalScript (bootstrap_node.js:353:27)
    at run (bootstrap_node.js:122:11)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:121:9)
    at bootstrap_node.js:504:3

节点版本

$ node --version
v6.11.2

最佳答案

简而言之,您将大括号视为 block statement ,而不是 object .

错误来自 label ,不能是 computed property name ,因为它需要是一个标识符,而不是一个计算属性。

第一个调用被定义为表达式,而在最后一种情况下则不是。

为了防止这种情况,您可以将表达式的大括号括在圆括号中。

eval("var other = 'b'; {a: 1, console.log('block!') };");
console.log(eval("var other = 'b'; ({a: 1, [other]: 2})[other];"));

关于javascript - 计算属性名称上的 JS 属性访问器在表达式与赋值中的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359164/

相关文章:

javascript - Jquery数据表: Removing row redirects to first page every time

javascript - typescript : fat arrow & this scope relation

javascript - ES7 中执行字符串对象的对象合并的最快方法是什么?

javascript - react 类中不必要的构造函数

python - 我的Python有什么问题?

mysql - 创建 mysql 表时出现错误 1064 (42000)

javascript - 从 Java 脚本 (TVML) 调用带有完成处理程序的 Swift 函数

javascript - JavaScript 的 Bitbar Cloud Appium 服务器端测试包内容

javascript - 关闭悬停功能未触发

php - magento-警告: require_once(app/Mage.php): failed to open stream: No such file or directory