gpt4 book ai didi

javascript - javascript中的对象方法和缩短的对象方法语法有什么区别?

转载 作者:行者123 更新时间:2023-12-05 03:46:26 24 4
gpt4 key购买 nike

最近在研究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");
}
};

To tell the truth, the notations are not fully identical. There aresubtle differences related to object inheritance (to be coveredlater), but for now they do not matter. In almost all cases theshorter syntax is preferred.

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

最佳答案

我的猜测是引用的文本是在谈论这样一个函数表达式不能使用 super 的事实:

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

关于javascript - javascript中的对象方法和缩短的对象方法语法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65296118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com