如何在不影响原始函数的情况下扩展(使用新名称)javascript 中的静态函数?
How do I extend (with a new name) a static function in javascript without affecting the original?
我在想出如何扩展静态函数 (momentjs) 以便我可以重写这些方法而不改变原始函数时遇到问题。
明确地说,我知道如何扩展实例的时刻来覆盖函数,但我想直接扩展库,所以我得到了我自己的命名实例moment
我可以像 momentjs 一样使用。
例如,我希望能够执行以下操作
extendedMoment().customFunction() //do something custom
extendedMoment().toString() //use customised toString() method
extendedMoment().format() //use the original momentjs method
我已经尝试了一些复制原型等选项,但编辑新 extendedMoment
函数的原型似乎会影响原来的原型。
更新:@PatrickRoberts
在下面回答
经过深入研究 the source, you can't really directly extend the library because there are several scoped functions which are not exposed, and moment()
is actually a wrapper of a wrapper of a wrapper of a wrapper of the constructor。因此,这是通过重用相同的扩展原型而不是在工厂扩展中分配作用域函数可以做的最好的事情:
function extendedMoment () {
return Object.setPrototypeOf(moment(), extendedMoment.prototype);
}
Object.setPrototypeOf(extendedMoment.prototype, moment.prototype);
Object.setPrototypeOf(extendedMoment, moment);
extendedMoment.prototype.toString = function toString () {
return this.format('YYYY-MM-DD');
};
console.log("Original: " + moment().toString());
console.log("Extended: " + extendedMoment().toString());
<script src="http://momentjs.com/downloads/moment.min.js"></script>
它的工作方式是在工厂扩展中用 extendedMoment.prototype
替换实例的原型(最初是 Moment.prototype
),为 [的所有实例重用相同的 toString
函数=16=].
编辑
我发现自己用 "constructor" 这个词来表示 extendedMoment
,所以我纠正了自己。它实际上是一个工厂扩展,因为它是@ZakHenry 指出的静态函数。对用词不当表示歉意。
我在想出如何扩展静态函数 (momentjs) 以便我可以重写这些方法而不改变原始函数时遇到问题。
明确地说,我知道如何扩展实例的时刻来覆盖函数,但我想直接扩展库,所以我得到了我自己的命名实例moment
我可以像 momentjs 一样使用。
例如,我希望能够执行以下操作
extendedMoment().customFunction() //do something custom
extendedMoment().toString() //use customised toString() method
extendedMoment().format() //use the original momentjs method
我已经尝试了一些复制原型等选项,但编辑新 extendedMoment
函数的原型似乎会影响原来的原型。
更新:@PatrickRoberts
在下面回答经过深入研究 the source, you can't really directly extend the library because there are several scoped functions which are not exposed, and moment()
is actually a wrapper of a wrapper of a wrapper of a wrapper of the constructor。因此,这是通过重用相同的扩展原型而不是在工厂扩展中分配作用域函数可以做的最好的事情:
function extendedMoment () {
return Object.setPrototypeOf(moment(), extendedMoment.prototype);
}
Object.setPrototypeOf(extendedMoment.prototype, moment.prototype);
Object.setPrototypeOf(extendedMoment, moment);
extendedMoment.prototype.toString = function toString () {
return this.format('YYYY-MM-DD');
};
console.log("Original: " + moment().toString());
console.log("Extended: " + extendedMoment().toString());
<script src="http://momentjs.com/downloads/moment.min.js"></script>
它的工作方式是在工厂扩展中用 extendedMoment.prototype
替换实例的原型(最初是 Moment.prototype
),为 [的所有实例重用相同的 toString
函数=16=].
编辑
我发现自己用 "constructor" 这个词来表示 extendedMoment
,所以我纠正了自己。它实际上是一个工厂扩展,因为它是@ZakHenry 指出的静态函数。对用词不当表示歉意。