Reputation: 161
Are the two defining methods pretty much the same? Is there anything I should watch out for?
// A.
function Dog(name, color, numLegs) {
this.name = name;
this.color = color;
this.numLegs = numLegs;
}
Dog.prototype.greet = function() {
return 'Bark!';
}
// B.
class Dog {
constructor(name = '', color = '', numLegs = 0) {
this.name = name;
this.color = color;
this.numLegs = numLegs;
}
greet() {
return 'Bark!';
}
}
I'm refactoring an old application and I'm wondering if it's safe to restructure all existing object functions from (A) to (B) as shown above.
Upvotes: 1
Views: 38
Reputation: 1695
class
in JavaScript is a syntactic sugar of constructor functions. When you work with functions, you are dealing with prototypes and prototypal inheritance, whereas in a class
it's more of coupling these actions together within a blueprint, which again makes use of functions and prototypes under the hood. In the first case, the function greet
is a prototype property of the function Dog
, meaning the instance of Dog
will be able to access the method greet
, and the same applies to the second case as well. (Make sure to use the new
keyword when instantiating objects in both cases).
Upvotes: 1
Reputation: 56
A js class is a beautified way of writing your first bit of code. So yes these two syntaxes do exactly the same thing.
Upvotes: 2