简体   繁体   中英

Class keyword and prototype in javascript

Now in Javascript, after ECMAScript 6 one can declare classes with the class keyword, which is nice for programmers who come from Java like languages (myself too).

class MyClass {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    mult() {
        return this.a * this.b;
    }
}

But one can even use the prototype way of defining classes.

// The same code as above, but with prototype.
function MyClass(a, b) {
    this.a = a;
    this.b = b;
}
MyClass.prototype.mult = function() {
    return this.a * this.b;
}

Are these two definitions of MyClass the same? Why? Can anyone help me in differentiating between "class" way of defining classes and "prototype" way of defining classes based on memory consumption, performance etc.? Thank You.

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

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

It's simple syntax alternative to prototype way.

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.

Source

Yes it is almost the same, since class is just sugar. The only difference I know is :

In this case

class MyClass() {}

you can't do var obj = MyClass() you must provide new . In the other case you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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