How to override a method in javascript class,

Skip the following snippet of code 1 and see what happens in the JS console:

My questions are about the last line in the snippet:

  • Why is it F.prototype.method;changed?
  • How to override Fcustom.prototype.methodso as not to change F.prototype.method?

Note. I use jQuery and underscore to extend the function.


  • 1 Excerpt from the test code:

    var F = function () {};
    F.prototype.method = function () {
        // some code
    }
    
    F.prototype.method; // it shows "some code"
    
    
    Fcustom = $.extend(true, F, {});
    
    _.extend(Fcustom.prototype, {
    method: function () {
        // other code
        }
    });
    
    Fcustom.prototype.method; // it shows "other code"
    
    F.prototype.method; // it shows "other code" instead of "some code" Why?
    
+5
source share
1 answer
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 :

+3
source

All Articles