超级关键字在这里出乎意料 [英] super keyword unexpected here

查看:340
本文介绍了超级关键字在这里出乎意料的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据ES6速记初始化程序,以下两种方法相同:

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对象中声明方法greeting的方式,应该相同.那么,为什么我们会出错?


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调用.
  • 方法的名称不会在方法的范围内绑定(不同于命名函数表达式).
  • Methods have a "HomeObject" which is what allows them to use super.
  • Methods are not constructable, i.e. they cannot be called with new.
  • The name of a method doesn't become a binding in the method's scope (unlike named function expressions).

这篇关于超级关键字在这里出乎意料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆