PointerToConstantChar
PointerToConstantChar

Reputation: 146

Javascript methods and copies

When you create a method in a constructor function like this:

var Something = function() {
    this.doSomething = function() {/* do something here */};
};

Javascript will make a copy of doSomething each time you create a new object with the Something constructor function.
But when you do it like this:

var Something = function() {

};
Something.prototype.doSomething = function() {/* Do something here */};

Does javascript still make a copy of doSomething each time you create an object with the Something constructor function, Or does doSomething in each object refer to the same thing for efficiency?

Upvotes: 0

Views: 32

Answers (2)

Karim
Karim

Reputation: 8632

The prototype is an object and as such is a reference, appending a method to it allow you to have only one spot in memory with the method shared by all your instances, that's why is the preferred way to declare methods.

function Something(){ 
  //as many spot in memory as the number of instances
 this.doSomething = function(){

 }
};

//only one spot in memory 
Something.prototype.doSomething = function(){

}

Upvotes: 0

Olga
Olga

Reputation: 1690

You can easily test this yourself, just run:

var a = new Something();
var b = new Something();
console.log(a.doSomething === b.doSomething);

In the case when you are defining the method in prototype the console.log should print true.

Anyway for all things JavaScript I suggest browsing MDN as it gives avery good introduction on most any subject. CSS and HTML too.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

Upvotes: 2

Related Questions