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?
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.
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With