我想从JavaScript中获取此哈希值:
hash= {:user_authenticated=>false, :user_email=>"nope"}
hash.user_authenticated
hash[user_authenticated]
hash["user_authenticated"]
hash[:user_authenticated]
似乎没什么用。我收到这个错误:
SyntaxError: invalid property id
答案 0 :(得分:6)
Javascript对象可能无法用像Ruby的哈希那样的火箭语法来表达。在采用ECMAScript 6时,Javascript实现已经能够使用相同的符号=>
用于匿名函数定义,尽管它们被称为箭头函数或俗称胖箭而不是哈希火箭。
对于简单函数,使用箭头语法和传统函数的定义之间没有区别。
var foo = function (s) { return s.toString() }
和
function foo(s) { return s.toString() }
相当于:
var foo = (s) => { return s.toString() }
另外,这些都等同于:
var foo = (s) => s.toString()
以及:
const foo = s => s.toString()
然而,当使用this
时,传统函数和箭头函数之间的选择很重要,因为传统定义的函数为this
创建了新的范围,而箭头函数则没有。来自the Mozilla doc on Arrow functions Mozilla Contributors的许可示例(CC-BY-SA 2.5下许可):
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
此处,p.age
将始终为0,因为递增的age
属于仅存在于内部函数内的this
,而不是Person
的实例是p
。当内部函数被定义为箭头函数时:
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(() => {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
p.age
将等于自p
创建以来的秒数,因为内部函数中的this
是实例' s this
。
有关详细信息,请参阅Mozilla docs。