请解释为什么会出现以下代码:
Element.prototype.addClass = function() {
const args = Array.prototype.slice.call(arguments);
return Element.prototype.classList.add.apply(this, args);
};
document.body.addClass('first', 'two');
https://jsfiddle.net/0s5gptfb/
导致错误Uncaught TypeError: Illegal invocation?
有上下文的东西?
发生了什么?
该方法
Element.prototype.classList.add属于 interfaceDomTokenList,并且必须在上下文中调用DomTokenList(在您的情况下,Element.classList)。在方法内部,
Element.prototype.addClass变量this指向一个实例Element,换句话说,您正试图add在错误对象的上下文中调用该方法。该怎么办?
您需要将正确的上下文传递给方法
Element.prototype.classList.add。例如像这样:这是JSFiddle 上的一个工作示例。