antonjs
antonjs

Reputation: 14318

How to re-define a method in a "javascript class"

Please run the following code snippet 1 and see what is happening in JS console:

My questions are regarding the last line in the snippet:

  1. Why is F.prototype.method; changed?
  2. How should I redefine Fcustom.prototype.method in order to not change F.prototype.method?

Note: I am using jQuery and underscore to extend the function.


Upvotes: 5

Views: 112

Answers (1)

Robin Maben
Robin Maben

Reputation: 23054

var obj = { myMethod : function() { 
              //some code
          }
};

var newObj = $.extend(true, {}, obj);

newObj.myMethod = function (){       
   //new method
};

newObj.myMethod();  //should call the new method

While,

obj.myMethod(); //still calls the old "//some code"

DEMO:

Upvotes: 3

Related Questions