gpt4 book ai didi

javascript - 如何在 "javascript class"中重新定义一个方法

转载 作者:搜寻专家 更新时间:2023-11-01 04:26:40 24 4
gpt4 key购买 nike

请运行以下代码片段 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"

DEMO :

关于javascript - 如何在 "javascript class"中重新定义一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12194795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com