Reputation: 116273
Surprisingly, this Apple page has Element.prototype
equal to undefined
, so I cannot use this awesome snippet of code.
Are there any reason for doing this?
Upvotes: 9
Views: 3856
Reputation: 32598
Apple is using the Coherent JS framework which has this 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
is originally a function, but it's being replaced and extended with a regular object. Only functions have .prototype
properties.
Workaround:
The prototype chain for any HTML element seems to be:
You should be able to attach your referenced code to the prototype to any of the bold objects in the chain and get the style for an html element. I would not recommend this in production code as modifying objects like that is generally considered harmful, but if you are just trying to export a style from another website, it should work well enough.
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.
Upvotes: 8
Reputation: 72241
In addition to what Dennis explained well, the easiest solution to avoid changing built-in objects (which people seem to love to do over and over, as Apple did on their site and Luc1245 did in the post you've mentioned).
A non-intrusive alternative is to run something like:
function exportStyles = ( function ( /* what Luc1245 posted */;
exportStyles.apply( /* this */ theElement, /* args */ []);
Upvotes: 1
Reputation: 4821
It seems that they have overwritten the default value of Element and assigned it the value of an object instance, which by default doesn't have the prototype property. Try the following in the console:
var a = {};
console.log(typeof a.prototype === 'undefined');
function abc() {}
Element = abc;
var b = new Element();
console.log(typeof b.prototype === 'undefined');
There isn't an universal reason to override built-in functions, so I'd guess it's probably because they thought it would make the most sense semantically (as it seems the Element object is used for DOM manipulation) and they don't have the possibility of conflicting with external libraries, which is why it's usually discouraged.
Upvotes: 0