似乎无法让 Element.setAttribute 与 webpack/babel 一起工作

Can't seem to get Element.setAttribute to work with webpack/babel

我有以下内容:

Element.prototype.makeDraggable = (elem = null) => {
    //this.draggable = true;
    this.setAttribute("draggable", "true");
    this.ondragstart = (e) => { e.dataTransfer.setData("text", elem ? elem.id : e.target.id); }
};

当浏览器访问该函数时,它会在第一行抛出错误:

Drag.js:7 Uncaught TypeError: n.setAttribute is not a function

其中 n 是元素的缩小名称,我是这么想的。

如图所示,this 似乎是 Element,但 n 是..我不知道它是什么。我做错了吗?

此时,如果我在控制台中this.draggable = true ,它工作得很好......你也可以看到我尝试在代码中这样做但这也不管用。

有什么想法吗?

你在调试器中看到的this实际this值;您在源代码视图中看到的 thisn 的源映射版本,而 n 的值不是您想要的。

你使用了箭头函数,所以你得到了词法this。这就是箭头函数的作用。要从调用时访问 this(将方法添加到原型时的一般意图),请使用非箭头函数:

Element.prototype.makeDraggable = function (elem = null) {
    //this.draggable = true;
    this.setAttribute("draggable", "true");
    this.ondragstart = (e) => { e.dataTransfer.setData("text", elem ? elem.id : e.target.id); }
};

另见

最后,扩展你最不能控制的原型——浏览器内置——被认为是一个坏主意。 (例如,您可能会与规范的未来扩展或与您使用的其他库发生冲突。)独立函数通常效果更好:

const makeDraggable = (target, elem = null) {
    target.draggable = true;
    target.ondragstart = (e) => { e.dataTransfer.setData("text", elem ? elem.id : e.target.id); }
};