Reputation: 127
Struggling to find documentation on this. I previously designed a class in JavaScript something like this:
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
area = function() {
return this.height * this.width;
}
}
It didn't work on JSFiddle and I had someone tell me I need to do it this way:
var Polygon = function(height, width) {
this.height = height;
this.width = width;
this.area = function() { return this.height * this.width; }
}
I've seen there's more than one way to do it, I was wondering if this was similar to C++ where you can do like... Polygon *myPoly = new Polygon(3, 4); to make a pointer, as opposed to Polygon myPoly(3, 4); or if it's just stylistic, and if so any insight as to why one of them doesn't work on JSFiddle and the other does.
Upvotes: 1
Views: 147
Reputation: 101680
Your first example isn't valid syntax. The correct way to write it would be:
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
}
This should work in JSFiddle if you are using a browser that supports classes, but there are some browsers out there that still do not (more on that below).
Regarding the difference between the two ways to write it, there are two things going on.
First, JavaScript is a very flexible language and there are usually dozens of ways to accomplish whatever you're trying to do.
Second, the class
syntax is a fairly new JavaScript feature that is not fully supported across all browsers that are widely in use (particularly, all versions of Internet Explorer). Under the surface, a class
is really just "syntactic sugar" for creating constructable objects the way that is shown in your second example, so the end result of those two code examples will be more or less the same.
So to respond to your C++ analogy, no, the two C++ code examples you provided do very different things while these two examples produce almost the same result. To get a result that is almost exactly the same, you could either change the first example to this:
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
this.area = function () { return this.height * this.width; };
}
}
or instead change the second example to this:
var Polygon = function(height, width) {
this.height = height;
this.width = width;
};
Polygon.prototype.area = function() { return this.height * this.width; };
Upvotes: 3
Reputation: 26075
You need to change your code from var area = ... to
get area() { return this.height * this.width; }
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes
https://jsfiddle.net/dwahlin/o93Lm0rc/
Upvotes: 1