2

我想从 JavaScript 中的这个哈希中获取一个值:

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

hash.user_authenticated

hash[user_authenticated]

hash["user_authenticated"]

hash[:user_authenticated]

似乎没有任何效果。我收到此错误:

SyntaxError: invalid property id

4

1 回答 1

8

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,而箭头函数则没有。Mozilla 贡献者关于箭头功能的 Mozilla 文档中的示例(根据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递增的 属于 a this,它只存在于内部函数中,而不是其实例Personis 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.agep将等于自创建以来的秒数,因为thisin 内部函数是实例的this.

有关详细信息,请参阅Mozilla 文档

于 2016-08-17T03:17:12.170 回答