super 关键字在这里出乎意料 [英] super keyword unexpected here
问题描述
根据 ES6 速记初始化器,以下 2 种方法是相同的:
According to ES6 shorthand initialiser, following 2 methods are same:
var person = {
name: "Person",
greet: function() {
return "Hello " + this.name;
}
};
在 ES6 中
var person = {
name: "Person",
greet() {
return "Hello " + this.name;
}
};
ES6 的方式与之前的方式有什么不同吗?如果不是,那么在它们内部使用super"也应该被视为相等,这是不正确的,请参见下面的两个变量:
Do the ES6 way is in anyway different from the previous way? If not then using "super" inside them should be also treated as equal, which doesn't hold true, please see below two variaiton:
let person = {
greet(){
super.greet();
}
};
Object.setPrototypeOf(person, {
greet: function(){ console.log("Prototype method"); }
});
person.greet();
以下失败
let person = {
greet: function(){
super.greet(); // Throw error: Uncaught SyntaxError: 'super' keyword unexpected here
}
};
Object.setPrototypeOf(person, {
greet: function(){ console.log("Prototype method"); }
});
person.greet();
<小时>
以上两个例子唯一的区别是我们在person对象中声明方法greet的方式,应该是一样的.那么,为什么会出现错误?
The only difference in above 2 examples is the way we declare method greet in person object, which should be same. So, why do we get error?
推荐答案
那么,为什么会出现错误?
So, why do we get error?
因为 super
仅在 方法.greet: function() {}
是一个正常"的属性/函数,而不是一个方法,因为它不遵循方法语法.
Because super
is only valid inside methods. greet: function() {}
is a "normal" property/function, not a method, because it doesn't follow the method syntax.
方法和普通函数定义的区别是:
The differences between a method and a normal function definition are:
- 方法有一个HomeObject",允许它们使用
super
. - 方法是不可构造的,即它们不能用
new
调用. - 方法的名称不会成为方法范围内的绑定(与命名函数表达式不同).
这篇关于super 关键字在这里出乎意料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!