What is equivalent to ES6 methods (class) in es5?

How will we use the polyfill es6 class methods in ES5?

I am reading a book, and she says the following:

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

    swingSword() {
        return true;
    }
}

coincides with

function Ninja(name) {
    this.name = name;
} 

Ninja.prototype.swingSword = function() {
    return true;
};

I'm just asking why we add swingSword in the prototype, and not inside the constructor function?

Since the function should be on the object, and not on the prototype chain.

Am I right or wrong?

+4
source share
2 answers

It must be on the prototype, methods are not data for each instance. You cannot think of any language that implements it in this way; the whole idea of ​​classes is to have a whole class of objects that have the same set of methods.

-, , . , 1000 == 1000 , "".

0

Ninja. , Ninja, Kunoichi, Ninja. , swingSword , Kunoichi .

, .

0

Source: https://habr.com/ru/post/1659974/


All Articles