与ES6中的原型等效 [英] Equivalent of Prototype in ES6

查看:103
本文介绍了与ES6中的原型等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从ES6开始,具有JavaScript的背景知识.我有个问题.我有一个ES6类,如下所示:

I am starting out in ES6 with background in JavaScript. I have a question. I have an ES6 class like the following:

class User{
 constructor(){
 }

 doSomething(){
 }
}

我的问题是,每次实例化此对象时,都会创建doSomething方法吗?在以前的JS中,我们可以取出doSomething并使用原型"创建它,以确保doSomething仅创建一次,而不是每次实例化该对象时都创建一次.但是,我注意到在ES6中获得相同效果的正确方法是肯定的.任何帮助将不胜感激.

My questions is does doSomething method get created each time we instantiate this object? In previous JS, we could take out doSomething and create it with "prototype" to ensure that doSomething is created once, not every time we instantiate the object. However, I am note sure about the correct way to achieve the same effect in ES6. Any help would be appreciated.

推荐答案

我的问题是,每次实例化此对象时,都会创建"doSomething"方法吗?

My questions is does "doSomething" method get created each time we instantiate this object?

不. class语法或多或少地是 语法糖 功能+原型. IE.结果(几乎)等于:

No. The class syntax is more or less just syntactic sugar for constructor function + prototype. I.e. the result is (almost) equivalent to:

function User() {}
User.prototype.doSomething = function() { };

查看Chrome产生的结果:

Look at the result Chrome produces:

但是,我注意到在ES6中获得相同效果的正确方法.

However, I am note sure about the correct way to achieve the same effect in ES6.

如前所述,class为您做到了.引入class的全部目的是使在prototype上创建构造函数和设置方法更容易(因此 syntactic sugar ).

As said, class does that for you. The whole point of introducing class is to make creating constructor functions and setting methods on prototype easier (hence syntactic sugar).

如果您想了解更多信息,请看

If you want to learn more, have a look at

ECMAScript 6中引入的JavaScript类是JavaScript上现有的基于原型的继承的语法糖.类语法不是,它向JavaScript引入了新的面向对象的继承模型. JavaScript类提供了一种更简单明了的语法来创建对象和处理继承.

JavaScript classes introduced in ECMAScript 6 are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

  • 查看全文

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