为什么Element.prototype未定义?

时间:2011-11-25 12:28:19

标签: javascript

令人惊讶的是,this Apple page Element.prototype等于undefined,因此我无法使用此awesome snippet of code

有没有理由这样做?

3 个答案:

答案 0 :(得分:8)

Apple正在使用具有此block of code

的Coherent JS框架
//  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等...)
  • HTML元素
  • 元素
  • 节点
  • 对象

您应该能够将引用的代码附加到原型中,链接到任何粗体对象,并获取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.

答案 1 :(得分:1)

除了丹尼斯解释得很好之外,最简单的解决方案是避免更换内置对象(人们似乎喜欢一遍又一遍地做,就像Apple在他们的网站上所做的那样,Luc1245在你提到的帖子中做了)

非侵入式替代方案是运行类似:

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

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

答案 2 :(得分:0)

似乎他们已经覆盖了Element的默认值,并为其分配了一个对象实例的值,默认情况下它没有prototype属性。在控制台中尝试以下操作:

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

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

没有普遍的理由来覆盖内置函数,所以我猜它可能是因为他们认为它在语义上最有意义(因为看起来Element对象用于DOM操作)并且他们不喜欢没有可能与外部库发生冲突,这就是为什么它通常不鼓励。