[英]How to replace a method without losing the original?
I'm replacing (overriding, improving, adding functionality to) a method in the prototype of the Date
object. 我正在
Date
对象的原型中替换(覆盖,改进,添加功能)方法。 Here is a simplified version of what I've done: 这是我所做的简化版本:
Date.prototype._toString = Date.prototype.toString;
Date.prototype.toString = function(mask) {
if(mask == undefined){return this._toString();}
//snip
//...
//snip
return date_string;
}
As I don't want to lose the standard method, I'm assigning the original method to a temporal variable and calling it if appropriate. 因为我不想丢失标准方法,所以我将原始方法分配给时间变量并在适当时调用它。
Is there a way of doing this without polluting the Date.prototype
namespace? 有没有办法在不污染
Date.prototype
命名空间的情况下执行此Date.prototype
?
What I'm asking is this same question , only in Javascript. 我问的是同样的问题 ,只有在Javascript中。
You can do it like this:- 你可以这样做: -
(function() {
var _toString = Date.prototype.toString;
Date.prototype.toString = function(mask) {
if (mask == undefined) { return _toString.call(this); }
//snip
}
})();
While the above solution is more elegant is the way that it doesn't pollute the Date.prototype, calls to the "new" toString will be slowed down because of the closure it involves. 虽然上面的解决方案更优雅的是它不会污染Date.prototype,但由于它涉及的闭包,对“new”toString的调用将会变慢。
It terms of speed, you'll be better off the way you mentioned in your question. 它的速度方面,你会比你在问题中提到的方式更好。 Try a loop that calls your code 20,000 times and then try the code submitted by Anthony.
尝试一个调用代码20,000次的循环,然后尝试Anthony提交的代码。
Depending on how often your code is called, you'll want to go one way or the other. 根据您的代码调用频率,您可能希望采用这种方式。
Cheers! 干杯!
Update: you can read this little sample from Google 更新:您可以从Google阅读这个小样本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.