火箭语法中的javascript对象

标签 javascript hashrocket

我想在 JavaScript 中从这个散列中获取一个值:

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

hash.user_authenticated

hash[user_authenticated]

hash["user_authenticated"]

hash[:user_authenticated]

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

语法错误:无效的属性 ID

最佳答案

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 是实例的 这个

更多信息请引用Mozilla docs .

关于火箭语法中的javascript对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24945537/

相关文章:

javascript - 这个 node.js 声明代码是 node.js 方式还是可以通过使用更少的逗号并分成更多行来改进?

ruby - "=>"中的 "rescue Exception => e"有什么作用?

javascript - 检查是否有重复值然后弹出一条消息谷歌脚本

javascript - 如何将字符串 "a,b,c,d..."转换为 a.b(c,d,...);执行

ruby - 哈希火箭被弃用了吗?

ruby-on-rails - 在 Ruby 中, "=>"是什么意思,它是如何工作的?

ruby - 将错误对象分配给 `rescue` 方法的变量时使用的语法 (=>) 是什么?

javascript - 来自 jQuery 的编程表单 POST 在文档就绪中不起作用

Javascript:在 'onload' 事件之后应用的事件处理程序如何处理页面完全加载之前发生的事件?