将 HTML 元素放在原型链中? [英] put HTML element in prototype chain?

查看:40
本文介绍了将 HTML 元素放在原型链中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个对象,通过将元素放在对象的原型链中来扩展 HTML 元素的功能.

I would like to create an object that extends the function of an HTML element by putting the element in the object's prototype chain.

我虽然可以使用以下内容来做到这一点:

I though I could do this with something like the following:

var el = document.createElement( "div" );
el.innerHTML = "foo";

var wrapper = Object.create( el );
alert( wrapper.innerHTML );

以上方法无效,而以下方法有效:

The above does not work, whereas the following does:

var el = document.createElement( "div" );
el.innerHTML = "foo";

var wrapper = Object.create( el );
alert( wrapper.__proto__.innerHTML );

为了找到给定的属性,需要明确地查看原型内部,这似乎很奇怪.

It seems odd that explicitly looking inside the prototype would be necessary to find a given property.

推荐答案

它不起作用,因为您在一个不是本机 DOM 元素并且没有任何元素的对象上使用 .innerHTML getter其内部插槽.

It does not work because you are using the .innerHTML getter on an object that is not a native DOM element and does have none of its internal slots.

我想创建一个对象,通过将元素放在对象的原型链中来扩展 HTML 元素的功能.

I would like to create an object that extends the function of an HTML element by putting the element in the object's prototype chain.

这是错误的方式.要扩展元素的功能,您需要将自定义函数放在其原型链中,以便仍然在元素本身上调用方法.您可以为此使用 Object.setPrototypeOf,或制作自己的 ES6 子class(可能还有 将其注册为自定义元素类型).

That's the wrong way round. To extend the functionality of an element, you need to put your custom function in its prototype chain, so that methods are still called on the element itself. You can use Object.setPrototypeOf for that, or make your own ES6 subclass (and possibly register it as a custom element type).

但最好的解决方案是简单地在元素周围放置一个包装对象.也看看 http://perfectkills.com/whats-wrong-with-extending-the-dom/.

But the best solution would be to simply put a wrapper object around the element. Also have a look at http://perfectionkills.com/whats-wrong-with-extending-the-dom/.

这篇关于将 HTML 元素放在原型链中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆