/ / Jak ponownie zdefiniować metodę w „klasie javascript” - javascript, jquery, underscore.js

Jak ponownie zdefiniować metodę w "klasie javascript" - javascript, jquery, underscore.js

Uruchom następujący fragment kodu 1 i zobacz, co się dzieje w konsoli JS:

Moje pytania dotyczą ostatniego wiersza fragmentu:

  1. Dlaczego jest F.prototype.method; zmienić?
  2. Jak mam przedefiniować Fcustom.prototype.method aby się nie zmieniać F.prototype.method?

Uwaga: Używam jQuery i podkreślenia do rozszerzenia funkcji.


  • 1 Fragment kodu testowego:

    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?
    

Odpowiedzi:

3 dla odpowiedzi № 1
var obj = { myMethod : function() {
//some code
}
};

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

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

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

Podczas,

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

PRÓBNY: