【问题标题】:What is the difference between object method and shortened object method syntax in javascript?javascript中的对象方法和缩短的对象方法语法有什么区别?
【发布时间】:2021-03-25 12:16:50
【问题描述】:

最近一直在研究JS OOP,停在下面一行(引用):

// these objects do the same

user = {
  sayHi: function() {
    alert("Hello");
  }
};

// method shorthand looks better, right?
user = {
  sayHi() { // same as "sayHi: function()"
    alert("Hello");
  }
};

说实话,这些符号并不完全相同。有 与对象继承相关的细微差别(待讨论 稍后),但现在它们无关紧要。在几乎所有情况下 首选较短的语法。

我还没有找到这个问题的答案。 那么,这两种符号之间的细微差别是什么?

【问题讨论】:

标签: javascript oop object methods


【解决方案1】:

我的猜测是引用的文字在谈论:

const object = {
  toString: function () {
    return "Hello World! " + super.toString();
  }
};

虽然速记可以使用super:

const object = {
  toString() {
    return "Hello World! " + super.toString();
  }
};

console.log(object.toString());

见:MDN Using super.prop in object literals

【讨论】:

    猜你喜欢
    • 2017-05-12
    • 2015-05-02
    • 2015-02-04
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2013-04-13
    相关资源
    最近更新 更多