gpt4 book ai didi

javascript - 重写原型(prototype)方法并调用原始方法

转载 作者:行者123 更新时间:2023-11-28 19:47:57 24 4
gpt4 key购买 nike

我想重写Html5 Canvas的drawImage函数。这是代码。

var p = CanvasRenderingContext2D.prototype.drawImage;
CanvasRenderingContext2D.prototype.drawImage = function() {
var len = arguments.length;
var ig, sx, sy, swidth, sheight, x, y, width, height
if (len === 3) {
p(arguments[0], arguments[1] * 2, arguments[2] * 2, this);
} else if (len === 5) {
//Uncaught TypeError: Illegal invocation.
p(arguments[0], arguments[1] * 2, arguments[2] * 2, arguments[3] * 2, arguments[4] * 2, this);
} else if (len === 9) {
p(arguments[0], arguments[1] * 2, arguments[2] * 2, arguments[3] * 2, arguments[4] * 2, arguments[5] * 2, arguments[6] * 2, arguments[7] * 2, arguments[8] * 2, this);
}
}

并按如下方式调用该函数。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

但是它在注释行中抛出错误。重写原型(prototype)方法后,如何调用原来的方法。

最佳答案

您必须说 p.callp.apply 才能在正确的上下文中执行它。

if (len === 3) {
p.call(this, arguments[0], arguments[1] * 2, arguments[2] * 2);
} else if (len === 5) {
p.call(this, arguments[0], arguments[1] * 2, arguments[2] * 2, arguments[3] * 2, arguments[4] * 2);
} else if (len === 9) {
p.call(this, arguments[0], arguments[1] * 2, arguments[2] * 2, arguments[3] * 2, arguments[4] * 2, arguments[5] * 2, arguments[6] * 2, arguments[7] * 2, arguments[8] * 2);
}

编辑:原因如下。当您调用 JavaScript 函数时,默认情况下,它在 window 上下文中执行。这意味着关键字 this 引用 window(它不应该引用;当您调用 drawImage 时,this 应该引用 canvas 元素) 。通过覆盖默认上下文window,您可以将其更改为正确的上下文。

示例:

var w = document.write;
// Error
w("Test");
// Works
w.call(document, "Test");

关于javascript - 重写原型(prototype)方法并调用原始方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23957861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com