Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript difference between MyClass.prototype = {} and MyClass.prototype.method [duplicate]

This is one thing I was wondering for a long time. But first example code for both

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 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?

like image 604
crashbus Avatar asked Oct 19 '22 10:10

crashbus


1 Answers

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 with Object.getPrototypeOf). The actual prototype of a constructor is Function.prototype since constructors are functions. Its prototype property will be the prototype of instances created through it but is not its own prototype.

like image 137
doldt Avatar answered Oct 22 '22 02:10

doldt