ES6类与构造函数相同吗? [英] Are ES6 classes the same as constructor functions?

查看:47
本文介绍了ES6类与构造函数相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解:ES6类基本上是构造函数,对吗?

As I understand it: ES6 classes are basically constructor functions, right?

当然,不必写这样的东西:

Of course with the benefit of not having to write stuff like this:

myFunction.prototype.myInheritablemethod= "someMethod";

这正确吗?

我之所以问是因为我知道有模块模式和显示模块模式,但是那不是ES6类的意思,对不对?

I'm asking because I'm aware there is the module pattern and the revealing module pattern, but those are not what ES6 classes are about, right?

推荐答案

引入了类,以围绕现有的JavaScript原型继承模型提供语法糖.以下...

Classes were introduced to provide syntactic sugar around the existing prototypal inheritance model of JavaScript. The following...

class Example {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  add() {
    return this.a + this.b;
  }
}

...基本上等同于此:

...is basically equivalent to this:

function Example(a, b) {
  this.a = a;
  this.b = b;
}
Example.prototype.add = function() {
  return this.a + this.b;
};

class 语法以及它提供的其他位(例如 extends static )使编写代码变得更加容易和清晰.处理继承.但是,由于它只是围绕现有技术的精髓,因此您可能首先应该正确理解ES6之前的继承.

The class syntax along with the other bits it provides (like extends and static) makes it much easier and clearer to write code that deals with inheritance. But since it's just sugar around existing techniques it would probably make sense for you to properly understand pre-ES6 inheritance first.

这篇关于ES6类与构造函数相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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