火箭语法中的javascript对象

rik*_*mbo 2 javascript hashrocket

我想从JavaScript中获取此哈希值:

hash=    {:user_authenticated=>false, :user_email=>"nope"}

hash.user_authenticated

hash[user_authenticated]

hash["user_authenticated"]

hash[:user_authenticated]
Run Code Online (Sandbox Code Playgroud)

似乎没什么用.我收到此错误:

SyntaxError: invalid property id

bsc*_*ter 6

Javascript对象可能无法用像Ruby的哈希那样的火箭语法来表达.由于采用了ECMAScript 6,Javascript实现已经获得了使用相同符号的能力,=>用于匿名函数定义,尽管它们被称为箭头函数或俗称为胖箭头而不是散列火箭.

对于简单函数,使用箭头语法和传统函数的定义之间没有区别.

var foo = function (s) { return s.toString() }
Run Code Online (Sandbox Code Playgroud)

function foo(s) { return s.toString() }
Run Code Online (Sandbox Code Playgroud)

相当于:

var foo = (s) => { return s.toString() }
Run Code Online (Sandbox Code Playgroud)

另外,这些都等同于:

var foo = (s) => s.toString()
Run Code Online (Sandbox Code Playgroud)

以及:

const foo = s => s.toString()
Run Code Online (Sandbox Code Playgroud)

但是,在使用时this,传统函数和箭头函数之间的选择很重要,因为传统定义的函数会创建新的范围this,而箭头函数则不会.来自Mozilla贡献者的Mozilla doc on Arrow函数的示例 (根据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();
Run Code Online (Sandbox Code Playgroud)

在此,p.age将始终为0,因为age时递增属于this其中仅内部函数中存在,而不是实例的Personp.当内部函数被定义为箭头函数时:

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();
Run Code Online (Sandbox Code Playgroud)

p.age将等于自p创建以来的秒数,因为thisin inner函数是实例的this.

有关更多信息,请参阅Mozilla文档.