JavaScript:什么时候使用Class还是原型? [英] JavaScript: When to use a Class vs. a prototype?

查看:287
本文介绍了JavaScript:什么时候使用Class还是原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道最新版本的JavaScript(ES6)现在支持创建类。我也理解在ES5和早期版本的JS中创建和使用对象的通常方法是创建对象原型。那么,使用类与下面的原型以及何时使用哪种方法有什么区别?

I understand that the latest version of JavaScript (ES6) now supports creating classes. I also understand that the usual way to create and work with objects in ES5 and earlier versions of JS was to create object prototypes. So, what is the difference between using a class vs. a prototype like below and when do you use either approach?:

类方法:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return "I have a " + this.carname + ".";
  }
}

mycar = new Car("Toyota");
document.getElementById("demo").innerHTML = mycar.present(); // outputs "I have a Toyota."

原型方法:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

//adding a new method to the prototype:

Person.prototype.name = function() {
  return this.firstName + " " + this.lastName;
};

var john = new Person("John", "Doe", 43, "Blue");
console.log(john.name); // outputs "John Doe"


推荐答案


那么,使用类与下面的原型以及何时使用哪种方法有什么区别?

So, what is the difference between using a class vs. a prototype like below and when do you use either approach?

要简单地回答您的问题,没有什么实际区别

To answer your question simply, there is no real difference.

直接来自 MDN网络文档定义


在ECMAScript 2015中引入的JavaScript类主要是语法上的糖,而不是JavaScript现有的基于原型的继承。

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

这篇关于JavaScript:什么时候使用Class还是原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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