This is one thing I was wondering for a long time. But first example code for both
var JavaScriptClass = function () {
};
JavaScriptClass.prototype = {
myMethodOne: function() {
},
myMethodTwo: function() {
}
};
var JavaScriptClass = function () {
};
JavaScriptClass.prototype.myMethodOne = function(){
};
JavaScriptClass.prototype.myMethodTwo = function(){
};
I saw both in lots of tutorials, examples and libraries (subjective Type A in the older ones).
For me it is more comfortable to use Type A especially in large classes, because you have to write less code. But as I know the compiler of coffeescript compiles the Class
statement to Type B.
Is there a considerable difference between Type A and B (e.g. performance, advantages with inheritance, or better IDE support) or is this only a "coding style" thing?
There is a considerable difference.
In Type A, you're reassigning the prototype property of the function, in Type B, you're extending it (by reassigning certain methods). This would not be different if nobody else touched the prototype, but actually functions come with a prototype property by default.
Try this: type into the console
var a=function(){console.log(123);};
Then access the prototype of this newly created function:
a.prototype;
In a browser environment this logs an object with a constructor
and a __proto__
attribute. If you do Type A, a.prototype will be your object entirely, in Type B, you're extending this object with methods myMethodOne
and myMethodTwo
.
As for the practical difference (which mostly plays a role when you want to use this function as a constructor function), particularly on why a function has a default prototype property at all (not to be confused with the prototype on the prototype chain of the created function), let me quote Eloquent Javascript, chapter 6:
It is important to note the distinction between the way a prototype is associated with a constructor (through its
prototype
property) and the way objects have a prototype (which can be retrieved withObject.getPrototypeOf
). The actual prototype of a constructor isFunction.prototype
since constructors are functions. Itsprototype
property will be the prototype of instances created through it but is not its own prototype.
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