JS 扩展方法的功能

2024-01-05

我正在尝试扩展 2dcontext 对象的某些方法的功能,但是我无法让它按照我想要的方式工作:我想重写一个方法,但我想从重写的方法中调用原始方法,例如这:

//First get the original context
var ctx = canvas.getContext("2d");

//Create a class which uses ctx as it's prototype
var ExtendedContext = function (){};
ExtendedContext.prototype = ctx;

//And extend a method
ExtendedContext.prototype.fillRect = function(x, y, width, height) {
    //Do some stuff
    this.prototype.fillRect(x, y, width, height); //Doesn't work
    //Do some more stuff
};

怎么称呼原来的fillRect我自己的方法中的方法?


您可以像这样存储原始函数的引用:

var oldFillRect = ctx.fillRect;

然后这样称呼它

ExtendedContext.prototype.fillRect = function() {
    //Do some stuff
    oldFillRect.apply(this, arguments);
    //Do some more stuff
};

这种技术有时被称为“鸭子打孔”或“功能钩子”。在这种特殊情况下,您还应该能够使用Object.getPrototypeOf方法获取原始函数引用。这看起来像

ExtendedContext.prototype.fillRect = function() {
    //Do some stuff
    Object.getPrototypeOf(ExtendedContext.prototype).fillRect.apply(this, arguments);
    //Do some more stuff
};

因此您甚至不需要存储引用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JS 扩展方法的功能 的相关文章

随机推荐