如何重新定义“;javascript类”;

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

本文关键字:javascript 何重新 定义      更新时间:2023-09-26

请运行以下代码片段1并查看JS控制台中发生了什么:

我的问题是关于摘录中的最后一行:

  1. 为什么更改F.prototype.method;
  2. 我应该如何重新定义Fcustom.prototype.method才能不更改F.prototype.method

注意:我使用jQuery和下划线来扩展函数。


  • 1测试代码片段:

    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?
    
var obj = { myMethod : function() { 
              //some code
          }
};
var newObj = $.extend(true, {}, obj);
newObj.myMethod = function (){       
   //new method
};
newObj.myMethod();  //should call the new method

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

演示: