Does ECMA6 allow prototype syntax as a best practice in JavaScript?
Example
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
JavaScript classes are introduced in ECMAScript 6 and are syntactic sugar over the existing JavaScript prototype-based framework. The class does not introduce a new object-oriented inheritance model for JavaScript. JS classes provide a much simpler, more straightforward syntax for creating objects and working with inheritance.
Does this mean that I should stop using the language term prototype
in my development when ECMA6 is final and used in this way using new syntactic sugar. I believe they are the same as others (from the same page):
// unnamed
var Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// named
var Polygon = class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
On the other hand, I can see it,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
var obj = {
foo() {},
bar() {}
};
How does it all fit together? What should I do with var myObj
? Can it have a constructor and methods, foo()
and bar()
like other languages? Is this acceptable?
var myObj = class myObj {
contructor(height, width){
this.height=height;
this.width=width;
},
foo(this.height) {alert('the height is ' + this.height)},
bar(this.height, this.width) {
alert('the width is ' + this.width);
var something = this.height + 5;
alert('the height is : ' + something);
}
};
var determine_something = new myObj(50,60);
determine_something.bar;
determine_something.foo;
(This did not work in the ECMA6 sandbox that I tried)
This gives no errors, but this.height
is undefined:
var myObj = class {
contructor(height, width){
this.height=height;
this.width=width;
}
foo() {
alert('the height is ' + this.height);
}
};
var determine_something = new myObj(50,60);
determine_something.foo();
EDIT: If I am not using prototype
and I want to add a new method, how do I do it with the new syntax?
source to share
Here is the revised / optimized version:
class MyObj {
contructor(height, width){
this.height = height;
this.width = width;
}
foo() {
alert(`the height is ${this.height}`)
}
bar() {
alert(`the width is ${this.width}`);
const something = this.height + 5;
alert(`the height is : ${something}`);
}
};
const determine_something = new MyObj(50,60);
determine_something.bar();
determine_something.foo();
source to share