如何替换一个方法而不丢失原来的方法?
我正在替换(覆盖、改进、添加功能)Date
对象原型中的一个方法。 这是我所做的事情的简化版本:
Date.prototype._toString = Date.prototype.toString;
Date.prototype.toString = function(mask) {
if(mask == undefined){return this._toString();}
//snip
//...
//snip
return date_string;
}
由于我不想丢失标准方法,因此我将原始方法分配给时间变量并在适当的情况下调用它。
有没有一种方法可以在不污染 Date.prototype
命名空间的情况下执行此操作?
我要问的是 同样的问题,仅在 Javascript 中。
I'm replacing (overriding, improving, adding functionality to) a method in the prototype of the Date
object. 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?
What I'm asking is this same question, only in Javascript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:-
You can do it like this:-
虽然上面的解决方案更优雅,但它不会污染 Date.prototype,但由于它涉及闭包,对“新”toString 的调用将会减慢。
就速度而言,您在问题中提到的方式会更好。 尝试一个调用您的代码 20,000 次的循环,然后尝试 Anthony 提交的代码。
根据调用代码的频率,您可能需要采用一种方式或另一种方式。
干杯!
更新:您可以阅读这个Google 的小示例
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.
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.
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