出人意料的是,this Apple page有Element.prototype
等於undefined
,所以我不能用這個awesome snippet of code。爲什麼Element.prototype未定義?
有什麼理由這樣做呢?
出人意料的是,this Apple page有Element.prototype
等於undefined
,所以我不能用這個awesome snippet of code。爲什麼Element.prototype未定義?
有什麼理由這樣做呢?
蘋果採用相干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元素似乎是:
你應該能夠將您的引用代碼附加到原型任何大膽的對象鏈,並獲得樣式的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.
看來,他們已經覆蓋元素的默認值,並分配一個對象實例的值,默認情況下不具有原型屬性。嘗試在控制檯以下:
var a = {};
console.log(typeof a.prototype === 'undefined');
function abc() {}
Element = abc;
var b = new Element();
console.log(typeof b.prototype === 'undefined');
沒有一個普遍的理由來覆蓋內置函數,所以我想這可能是因爲他們認爲這將使最有意義的語義(因爲它似乎元素對象用於DOM操作),它們不可能與外部庫衝突,這就是爲什麼它通常不鼓勵。
除了丹尼斯很好地解釋,以避免改變最簡單的解決方案內置的對象(人似乎喜歡做一遍又一遍,像蘋果那樣在其網站上和Luc1245在後沒有你已經提到)。
一種非侵入式的替代方法是運行類似:
function exportStyles = (function (/* what Luc1245 posted */;
exportStyles.apply(/* this */ theElement, /* args */ []);
你應該添加一個這樣的答案到鏈接的問題。 –
'Element.prototype === undefined'是一個比較。這沒有做任何事情。 – Tomalak
不確定爲什麼會出現這種情況,但您可以在該片段中使用HTMLElement而不是Element。 – pradeek
您可能會感興趣的發現[本條](http://perfectionkills.com/whats-wrong-with-extending-the-dom/)。 – smendola