Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the equivalent of ES6 methods(class) in es5?

How would we polyfill es6 class methods into ES5?

I am reading a book and it says the following:

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

    swingSword() {
        return true;
    }
}

is the same as

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

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

I am just asking why are we adding the swingSword on the prototype and not inside the constructor function?

Because the function should be on the object and not on the prototype chain.

Am i right or wrong?

like image 868
Sourav Jaiswal Avatar asked Nov 06 '16 07:11

Sourav Jaiswal


People also ask

Are there classes in ES5?

In the ES5 version, there are no classes; a function is used to make an object directly. However, the ES6 version uses the keyword class to define a class. The underlying concept is more or less the same. ES6 just cleans up the syntax.

Is ES6 compatible with ES5?

As of now, there are no browsers that fully support the ES6 features; however, we can convert the ES6 code to the ES5 code by using the transpilation. There are two major compilers Babel and Traceur, which are used to convert the ES6 code to ES5 code as part of the build process.

What is ES5 ES6?

ECMA script is a trademarked scripting language specification defined by Ecma international. The fifth edition of the same is known as ES5. ECMA script is a trademarked scripting language specification defined by Ecma international. The sixth edition of the same is known as ES6.


1 Answers

It should be on the prototype, methods are not per-instance data. Can't think of any language that implements it that way, the whole idea of classes is to have a whole class of objects that have the same set of methods.

If it was put it inside the constructor function, it would be a unique function per instance made with the constructor. e.g, 1000 objects == 1000 functions, per "method".

like image 108
Casper Beyer Avatar answered Oct 04 '22 23:10

Casper Beyer