2011-11-25 131 views
9

出人意料的是,this Apple pageElement.prototype等于undefined,所以我不能用这个awesome snippet of code为什么Element.prototype未定义?

有什么理由这样做呢?

+3

'Element.prototype === undefined'是一个比较。这没有做任何事情。 – Tomalak

+1

不确定为什么会出现这种情况,但您可以在该片段中使用HTMLElement而不是Element。 – pradeek

+0

您可能会感兴趣的发现[本条](http://perfectionkills.com/whats-wrong-with-extending-the-dom/)。 – smendola

回答

8

苹果采用相干JS框架,它有这个block of code

// Trick picked up from Prototype to get around IE8's fixed Element & Event 
(function() { 
    var element = this.Element; 
    this.Element = {}; 
    Object.extend(this.Element, element || {}); 
}).call(window); 

window.Element原本是一个功能,但它被替换并用常规的对象扩展。只有函数具有.prototype属性。

解决方法:

原型链任何HTML元素似乎是:

  • 具体元素类型(HTMLBodyElement,HTMLDivElement等...)
  • HTMLElement的
  • 节点
  • 对象

你应该能够将您的引用代码附加到原型任何大胆的对象链,并获得样式的HTML元素。 我不会在生产代码建议将此作为改变这样的对象通常是considered harmful,但如果你只是想一个风格从其他网站导出,它应该工作不够好。

Object.prototype.exportStyles = (function() { //Works if you use it on an element, the code will protect you from yourself if you try to use it on regular objects. 
HTMLElement.prototype.exportStyles = (function() { //Safer because it is farther down the inheritance line, affecting fewer objects. 
                 //Avoiding name collisions and other surprises. 
0

看来,他们已经覆盖元素的默认值,并分配一个对象实例的值,默认情况下不具有原型属性。尝试在控制台以下:

var a = {}; 
console.log(typeof a.prototype === 'undefined'); 

function abc() {} 
Element = abc; 
var b = new Element(); 
console.log(typeof b.prototype === 'undefined'); 

没有一个普遍的理由来覆盖内置函数,所以我想这可能是因为他们认为这将使最有意义的语义(因为它似乎元素对象用于DOM操作),它们不可能与外部库冲突,这就是为什么它通常不鼓励。

1

除了丹尼斯很好地解释,以避免改变最简单的解决方案内置的对象(人似乎喜欢做一遍又一遍,像苹果那样在其网站上和Luc1245在后没有你已经提到)。

一种非侵入式的替代方法是运行类似:

function exportStyles = (function (/* what Luc1245 posted */; 

exportStyles.apply(/* this */ theElement, /* args */ []); 
+0

你应该添加一个这样的答案到链接的问题。 –