如何用自定义函数替换javascript原型 [英] How to replace javascript prototype with custom function
本文介绍了如何用自定义函数替换javascript原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// I am trying to make a clone of String's replace function
// and then re-define the replace function (with a mind to
// call the original from the new one with some mods)
String.prototype.replaceOriginal = String.prototype.replace
String.prototype.replace = {}
下一行现在坏了 - 我该如何修复?
This next line is now broken - how do I fix?
"lorem ipsum".replaceOriginal(/(orem |um)/g,'')
推荐答案
唯一可能的问题是你的代码被执行了两次,导致出现问题:真正的原始 .replace
会消失.
The only possible issue is that your code is executed twice, which causes problems: The real original .replace
will disappear.
为避免此类问题,我强烈建议使用以下通用方法替换内置方法:
To avoid such problems, I strongly recommend to replace built-in methods using the following general method:
(function(replace) { // Cache the original method
String.prototype.replace = function() { // Redefine the method
// Extra function logic here
var one_plus_one = 3;
// Now, call the original method
return replace.apply(this, arguments);
};
})(String.prototype.replace);
- 这允许多种方法修改而破坏现有功能
- 上下文由
.apply()保留代码>
:通常,this
对象对于(原型)方法至关重要.
这篇关于如何用自定义函数替换javascript原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文