增加DOM元素节点的原型? [英] Augmenting the prototype of DOM element nodes?

查看:152
本文介绍了增加DOM元素节点的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何通过增加Object的原型来增加每个对象的新方法:

  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屋!

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