Uruchom następujący fragment kodu 1 i zobacz, co się dzieje w konsoli JS:
Moje pytania dotyczą ostatniego wiersza fragmentu:
- Dlaczego jest
F.prototype.method;
zmienić? - 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 № 1var 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"