Example,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JS classes provide a much simpler and clearer syntax to create objects and dealing with inheritance.
Does this mean I should stop using the language term prototype in my development, when ECMA6 is final and craft like this using the new syntactic sugar. I believe they are the same other than that (from 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 see this,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
var obj = {
foo() {},
bar() {}
};
How does this all fit together? What would I do with var myObj? Can it have a constructor and the methods foo() and bar() like other languages? Is this allowable?
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 an ECMA6 sandbox 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 do not use prototype, and I want to add a new method, how do I do it with the new syntax?
Here is the fixed/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();
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