简体   繁体   English

JavaScript有课吗?

[英]Does JavaScript have classes?

A friend and I had an argument last week.上周我和一个朋友吵架了。 He stated there were no such things as classes in JavaScript.他说 JavaScript 中没有类之类的东西。

I said there was as you can say var object = new Object()我说过有如你所说的var object = new Object()

He says "as there is no word class used. It's not a class."他说“因为没有使用单词class它不是 class。”

Who is right?谁是对的?

Edit: July 2017编辑:2017 年 7 月

JavaScript classes introduced in ECMAScript 2015 are primarily 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. JavaScript classes introduced in ECMAScript 2015 are primarily 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 .

- Mozilla ES6 Classes: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes - Mozilla ES6 类: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Technically, the statement "JavaScript has no classes" is correct.从技术上讲,“JavaScript 没有类”这句话是正确的。

Although JavaScript is object-oriented language, it isn't a class-based language —it's a prototype-based language .尽管 JavaScript 是面向对象的语言,但它不是基于类的语言——它是基于原型的语言 There are differences between these two approaches, but since it is possible to use JavaScript like a class-based language, many people (including myself) often simply refer to the constructor functions as "classes".这两种方法之间存在差异,但由于可以像基于类的语言一样使用 JavaScript,因此许多人(包括我自己)通常将构造函数简单地称为“类”。

Javascript is an object oriented programming language, nevertheless in 2015 with ECMA script 6 classes have been introduced and now is correct to use them like other class based languages like Java. Javascript 是一种面向对象的编程语言,但在 2015 年 ECMA 脚本中引入了 6 个类,现在可以像 Java 等其他基于类的语言一样使用它们。 Of course as pointed out by the user codemagician in his/her comment, there are some deep differences between how classes work in js and java or other "class based" programming languages.当然,正如用户代码魔术师在他/她的评论中指出的那样,类在 js 和 java 或其他“基于类”的编程语言中的工作方式之间存在一些深刻的差异。

Nevertheless now in js programming it is possible to use for example code like:不过现在在 js 编程中可以使用以下示例代码:

class Animal { 
  constructor(name) {
    this.name = name;
  }


class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes来源: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

That has something in common with classical class-based languages.这与经典的基于类的语言有一些共同之处。 The problems still is the browser support of this new technology that is just at start at the moment.问题仍然是这种新技术的浏览器支持,目前才刚刚开始。 So it still is not good to use it on productions products.所以在生产产品上使用它仍然不好。 But I don't have any doubt that this issue is going to be solved fast.但我毫不怀疑这个问题会很快得到解决。

Hence the question remains if js has become a class-based programming language because of the implementation of this new features or does it still remain an object prototyping oriented programming language.因此,问题仍然存在,js 是否因为实现了这个新特性而成为一种基于类的编程语言,或者它仍然是一种面向对象原型的编程语言。

In Javascript pretty much everything is an object (objects can inherit from other objects).在 Javascript 中几乎所有东西都是一个object (对象可以从其他对象继承)。 It does not have classes in the classical sense.它没有经典意义上的classes

Although you can reproduce most of the functionality of traditional class definition / instantiation by function prototyping.虽然您可以通过函数原型来重现传统类定义/实例化的大部分功能。

Listen to Douglas Crockford's talk here:在这里听道格拉斯·克罗克福德 (Douglas Crockford) 的演讲:
http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2 http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2

He directly addresses your question in his presentation:他在演讲中直接回答了你的问题:

The most controversial feature of the language is the way it does inheritance, which is radically different than virtually all other modern languages.该语言最具争议的特征是它进行继承的方式,这与几乎所有其他现代语言完全不同。 Most languages use classes – I call them 'classical languages' – JavaScript does not.大多数语言都使用类——我称它们为“经典语言”——JavaScript 没有。 JavaScript is class free. JavaScript 是类免费的。 It uses prototypes.它使用原型。 For people who are classically trained who look at the language, they go: well, this is deficient.对于那些受过经典训练的人来说,他们会看语言,他们会说:嗯,这是有缺陷的。 You don't have classes, how can you get anything done?你没有课,你怎么做事? How can you have any confidence that the structure of your program's going to work?你怎么能相信你的程序结构会起作用? And they never get past that.他们永远不会超越这一点。 But it turns out…但事实证明……

By "language X has classes" people usually mean support of object oriented programming.人们所说的“X 语言有类”通常是指支持面向对象编程。

Yes, Javascript is an object oriented language.是的,Javascript 是一种面向对象的语言。

From You-Dont-Know-JS book at https://github.com/getify/You-Dont-Know-JS来自https://github.com/getify/You-Dont-Know-JS 的You-Dont-Know-JS

Chapter 4: Mixing (Up) "Class" Objects第 4 章:混合(上)“类”对象

... ...

JS has had some class-like syntactic elements (like new and instanceof) for quite awhile, and more recently in ES6, some additions, like the class keyword. JS 已经有一些类似类的语法元素(比如 new 和 instanceof)有一段时间了,最​​近在 ES6 中增加了一些,比如 class 关键字。

But does that mean JavaScript actually has classes?但这是否意味着 JavaScript 实际上有类? Plain and simple: No简单明了:没有

I am not going to copy and past other parts here but encourage to read chapter 3 & chapter 4 and run samples.我不会在这里复制和跳过其他部分,但鼓励阅读第 3章和第 4 章并运行示例。

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch3.md https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch3.md

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch4.md https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch4.md

When I think of classes I think of types and the fact that classes allow me to define new types.当我想到类时,我会想到类型以及类允许我定义新类型的事实。 In js you can't create new types.在 js 中你不能创建新类型。 You can do all sorts of fancy oo stuff with prototypes but the fact that everything is still an object really hits home the class-less nature of js.你可以用原型做各种花哨的 oo 东西,但一切仍然是一个对象的事实确实让 js 的无类特性成为现实。 I think that people using 'class' terminology when talking about js confuses the js as a prototype language vs js as a classical language even more than the ugly new operator.我认为人们在谈论 js 时使用“类”术语,将 js 作为原型语言与作为经典语言的 js 混淆,甚至比丑陋的新运算符更容易混淆。 In short, just because js is OO doesn't imply that classes need to exist.简而言之,仅仅因为 js 是 OO 并不意味着类需要存在。

To add in with the other answers, javascript does not have classes, although I'm starting to see statements where it is described as something like classes, but I believe that just confuses the issue.要添加其他答案,javascript 没有类,尽管我开始看到将其描述为类之类的语句,但我相信这只会混淆问题。

JavaScript has prototypes, not classes, but they accomplish the same thing, prototypes are objects that define objects, hence the confusion. JavaScript 有原型,而不是类,但它们完成相同的事情,原型是定义对象的对象,因此混淆。

A prototype is a representation of private internal state that a class would manage in Java for example.例如,原型是类将在 Java 中管理的私有内部状态的表示。 Instead of putting that internal state in a class and presenting an interface for manipulating behaviour, as in java, JavaScript exposes the data structure for JavaScript programs to manipulate directly. JavaScript 没有像在 Java 中那样将内部状态放在一个类中并提供用于操作行为的接口,而是公开了供 JavaScript 程序直接操作的数据结构。

This is the best description I've found on the subject,Prototypes are not Classes .这是我在这个主题上找到的最好的描述,Prototypes 不是 Classes

In simple words - Yes.简单来说 - 是的。 All you need is Babel.js transpiler, because all browsers does not support it except Chrome browser.你只需要 Babel.js 转译器,因为除 Chrome 浏览器外,所有浏览器都不支持它。 A JavaScript class is a type of function. JavaScript 类是一种函数。 Classes are declared with the class keyword.类是用 class 关键字声明的。 We use function expression syntax to initialize a function and class expression syntax to initialize a class.我们使用函数表达式语法来初始化一个函数和类表达式语法来初始化一个类。

Here is an example of JavaScript class using function:下面是一个使用函数的 JavaScript 类示例:

 class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Getter get area() { return this.calcArea(); } // Method calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area); // 100

Although JavaScript didn't have classes prior to ES6, class-like behavior could be implemented in ES5 by sealing objects (thereby making objects non-extensible).尽管 JavaScript 在 ES6 之前没有类,但在 ES5 中可以通过密封对象(从而使对象不可扩展)来实现类的行为。 In a sealed object, new properties and methods cannot be added and properties are not configurable.在密封的对象中,不能添加新的属性和方法,并且属性是不可配置的。 Property values can still be set and read.仍然可以设置和读取属性 I say class-like, because there's one caveat.我说类,因为有一个警告。 A sealed object's method definitions can still be modified.密封对象的方法定义仍然可以修改。 That's because property values can still be set, unless you change all method properties to be non-writeable -- at which point you've reproduced class behavior pretty closely using ES5.这是因为仍然可以设置属性值,除非您将所有方法属性更改为不可写——此时您已经使用 ES5 非常接近地重现了类行为。

 class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Getter get area() { return this.calcArea(); } // Method calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area); // 100

Yes.是的。 Yes, javascript has classes and objects.是的,javascript 有类和对象。 This is an example of making blockchain by using javascript/NodeJS classes and objects:-这是使用 javascript/NodeJS 类和对象制作区块链的示例:-

// coded by Alfrick Opidi in Smashing Magazine blog
// https://www.smashingmagazine.com/2020/02/cryptocurrency-blockchain-node-js/

const SHA256 = require('crypto-js/sha256');
const fs = require('fs')

class CryptoBlock{
    constructor(index, timestamp, data, precedingHash=" "){
     this.index = index;
     this.timestamp = timestamp;
     this.data = data;
     this.precedingHash = precedingHash;
     this.hash = this.computeHash();     
    }
    computeHash(){
        return SHA256(this.index + this.precedingHash + this.timestamp + JSON.stringify(this.data)).toString();
    }   
}

class CryptoBlockchain{
    constructor(){
        this.blockchain = [this.startGenesisBlock()];     
    }
    startGenesisBlock(){
        return new CryptoBlock(0, "01/01/2020", "Initial Block in the Chain, its also called genisis", "0");
    }
    obtainLatestBlock(){
        return this.blockchain[this.blockchain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.precedingHash = this.obtainLatestBlock().hash;
        newBlock.hash = newBlock.computeHash();        
        this.blockchain.push(newBlock);
    }
}

 let smashingCoin = new CryptoBlockchain();

smashingCoin.addNewBlock(new CryptoBlock(1, "01/06/2020", {sender: "Iris Ljesnjanin", recipient: "Cosima Mielke", quantity: 50}));
smashingCoin.addNewBlock(new CryptoBlock(2, "01/07/2020", {sender: "Vitaly Friedman", recipient: "Ricardo Gimenes", quantity: 100}) );
fs.writeFile('genisis.json', JSON.stringify(smashingCoin), function (err) {
    if (err) throw err;
    console.log('Saved!');
  }); 
console.log(JSON.stringify(smashingCoin, null, 4));

Javascript is more of an Object based programming language rather than Object oriented programming language. Javascript 更像是一种基于 Object 的编程语言,而不是面向 Object 的编程语言。

AFAIK Javascript use the prototype concept and it's not OO. AFAIK Javascript 使用原型概念,而不是面向对象。 That's means that you can't use the typical concepts of OOP like inheritance or polymorphism.这意味着您不能使用 OOP 的典型概念,如继承或多态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM