1

I'd like to know the following about this example code:

1. What is the difference between these two? 2. When or under which scenarios one will be used or preferred over the other? 3. Can I achieve inheritance with both methods or only with prototype?

//e.g 1 without prototype
Test = function(){
 this.val = null;
 this.getVal = function(){
    return this.val;
 }
 this.setVal(a){
    val = a;
 }
}



//eg 2 with prototype.
Test2 = function(){
    this.val = null;
}
Test2.prototype.getVal = function(){
   return this.val;
}
Test2.prototype.setVal = function(value){
   this.val = value;
}

As pointed out by one of the answerer the top one is duplicating the methods and the second one is sharing the methods. Can somebody please explain what is the difference between duplicating and sharing [I am newbie to JS...to me it sounds the same because they are going to return the same result.]

Taimoor
  • 167
  • 3
  • 12
  • First one duplicates methods for new instances. Second one shares methods. – elclanrs Jan 15 '14 at 22:49
  • 1. prototype methods are shared and exist only once 2. privacy 3. with both – Bergi Jan 15 '14 at 23:46
  • Thanks for the answers. Can you please clarify whats the difference between duplicate methods vs sharing method. I am a newbie to JS... – Taimoor Jan 16 '14 at 00:47

0 Answers0