请运行以下代码片段 1 并查看 JS 控制台中发生了什么:
我的问题是关于代码段的最后一行:
- 为什么
F.prototype.method;
改变了? - 我应该如何重新定义
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/