Javascript difference between MyClass.prototype = {} and MyClass.prototype.method

This is one thing I've been thinking about for a long time. But the first code example for

Type A

var JavaScriptClass = function () { }; JavaScriptClass.prototype = { myMethodOne: function() { }, myMethodTwo: function() { } }; 

Type B

 var JavaScriptClass = function () { }; JavaScriptClass.prototype.myMethodOne = function(){ }; JavaScriptClass.prototype.myMethodTwo = function(){ }; 

I have seen so many textbooks, examples, and libraries (subjective type A in older ones).

It’s more convenient for me to use Type A especially in large classes, because you need to write less code. But, as I know, the coffeescript compiler compiles the Class statement to type B.

Is there a significant difference between types A and B (for example, performance, inheritance benefits, or better IDE support) or is it just a "coding style"?

+5
source share
1 answer

There is a significant difference.

In type A, you reassign the property of the function prototype, in type B, you extend it (by reassigning certain methods). This will not be different if no one touches the prototype, but in fact the functions have the prototype property by default.

Try the following: type in console

 var a=function(){console.log(123);}; 

Then access the prototype of this newly created function:

 a.prototype; 

In a browser environment, this log registers an object with the constructor and __proto__ . If you make type A, then a.prototype will be your entire object, in type B, you extend this object with the methods myMethodOne and myMethodTwo .

Regarding the practical difference (which basically plays a role when you want to use this function as a constructor function), especially about why the function has a prototype property by default (not to be confused with the prototype prototype chain of the created function), let me quote Eloquent Javascript, Chapter 6:

It is important to note the difference between how a prototype is associated with a constructor (through its prototype property) and how objects have a prototype (which can be obtained using Object.getPrototypeOf ). The actual prototype of the Function.prototype constructor, since constructors are functions. The prototype property will be the prototype of instances created through it, but is not its own prototype.

+3
source

All Articles