gpt4 book ai didi

javascript - 替换 DOM 元素对象的 __proto__

转载 作者:行者123 更新时间:2023-11-30 17:27:09 24 4
gpt4 key购买 nike

所以基本上我想通过以下代码扩展某种类型的 DOM 元素:

var element = document.createElement("div");
var proto = Object.create(HTMLDivElement.prototype);
proto.newMethod = function() {console.log("Good.");};
proto.newConst = Math.PI / 2;
element.__proto__ = proto;

此代码在 Chrome、Firefox 和 IE11 中有效(IE10 未测试,但它可能会有效),但我不确定它是否是正确的 JavaScript 以及它是否会在未来继续工作,因为无论如何这段代码正在破解部分在 JavaScript 之外的 DOM 元素。有人可以解释它是如何工作的吗?我不完全理解这一点,我需要知道这种方法是否可靠。谢谢。


好吧,为了让事情更清楚,我知道我应该使用 Object.create() 来指定原型(prototype),但真正的问题是元素对象很特殊,不可能那样做。上面的代码更像是一种解决方法,这就是我问这个问题的原因。


Google 的 Polymer 改变了 DOM 对象的 __proto__ (code, line 259):

function implement(element, definition) {
if (Object.__proto__) {
element.__proto__ = definition.prototype;
} else {
customMixin(element, definition.prototype, definition.native);
element.__proto__ = definition.prototype;
}
}

那么,我应该相信这种方法,因为 Google 使用它吗?

最佳答案

来自 Mozilla Developer Network :

The __proto__ property is deprecated and should not be used. Object.getPrototypeOf should be used instead of the __proto__ getter to determine the [[Prototype]] of an object. Mutating the [[Prototype]] of an object, no matter how this is accomplished, is strongly discouraged, because it is very slow and unavoidably slows down subsequent execution in modern JavaScript implementations. However, Object.setPrototypeOf is provided in ES6 as a very-slightly-preferred alternative to the __proto__ setter.

一般来说,修改 Array、String 甚至 HTMLElement 等原生原型(prototype)是一种不好的做法,详情请见 here ,但如果您控制当前上下文中的所有内容,您可以通过添加一些额外的功能来修改原型(prototype),风险自负,以实现您想要的效果。如果您可以保证您的代码不与其他代码冲突并且性能足迹可以忽略不计,那么您可以自由选择您的路径。

你的方法:

SomeHTMLElementInstance.__proto__ = newPrototype;

// or a general case like:

SomeHTMLElementPrototypeConstructor.prototype.newMethod = function () {
// Do something here
}

推荐方法:

var SomeElementWrapper = function (someParams) {
this.container = document.createElement('SomeHTMLElement');
}

SomeElementWrapper.prototype.someMethod = function () {
// Do something with this.container without modifying its prototype
}

关于javascript - 替换 DOM 元素对象的 __proto__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24014059/

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