增加DOM元素节点的原型? [英] Augmenting the prototype of DOM element nodes?
问题描述
Object.prototype.foo = function(){};
但是,是否可以为DOM元素节点定义新的方法? DOM元素节点对象是否有原型?还是有一个DOM节点的原型?
还是只为内置对象存在原型对象?
p>是的,但不是在所有的浏览器。 Internet Explorer 8支持DOM原型(在一定程度上支持),如Firefox,Chrome,Opera和Safari一样。
HTMLElement.prototype .toggle = function(){
this.style.display = this.style.display =='none'? '' : '没有';
}
很多人认为通过原型扩展DOM对象是不好的做法。康卡斯有关于这个主题的伟大文章: http://perfectionkills.com/什么,错与延伸最DOM / 。然而,DOM原型允许我们在不支持它们的环境中实现基于标准的方法,这很像ECMAScript第5版方法的垫片。
I know how to add new methods to every object - by augmenting the Object's prototype:
Object.prototype.foo = function() { };
But, is it possible to define new methods for DOM element nodes only? Do DOM element node objects have a prototype? Or is there maybe a prototype for DOM nodes in general?
Or do prototype objects only exist for built-in objects?
Yes, but not in all browsers. Internet Explorer 8 supports DOM prototypes (to a certain extent), as do Firefox, Chrome, Opera and Safari.
HTMLElement.prototype.toggle = function () {
this.style.display = this.style.display == 'none' ? '' : 'none';
}
Many consider it bad practice to extend DOM objects via their prototype. Kangax has a great article on the subject: http://perfectionkills.com/whats-wrong-with-extending-the-dom/. However, DOM prototypes allow us to implement standards-based methods in environments that don't support them yet, much like shims for ECMAScript 5th Edition methods.
这篇关于增加DOM元素节点的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!