This is not a question about how to extend JS natives and I am well aware of the "dangers" involved with such activity. I am only trying to get a deeper understanding of how JavaScript works. Why is it that if I write the following:
CSSStyleSheet.prototype.sayHi = function() {
console.log('CSSStyleSheet says hi!');
};
var test = new CSSStyleSheet;
test.sayHi(); // Console output: CSSStyleSheet says hi!
I get the expected output from the sayHi function. But if I then query a style element and produce a CSSStyleSheet object from it via the sheet property, the sayHi function is not defined:
var styleElm = document.querySelector('style'),
sheet = styleElm.sheet;
console.log('sheet', sheet) // Console output: sheet CSSStyleSheet {ownerRule: null,...
sheet.sayHi(); // Console output: Uncaught TypeError: sheet.sayHi is not a function
What is the reason for this? What would I have to do to make the sayHi function available to a CSSStyleSheet object produced via the sheet property - is it even possible?
The test was run in Chrome.
EDIT:
The reason I am looking into this is because I am trying to weigh my options when it comes to simplifying existing code. I have made an API to manipulate internal styles of a document loaded in an iFrame. It works as intended, but I would like to simplify the code if possible. It builds on the CSSOM API, which allows access to individual CSS style rules via numerical indexes. Having numerical indexes as the only way to access CSS rules seems quite rudimentary since you would never request a particular index unless you knew what rule the index pointed to. That is, you would always need to have info about the selector text. But it is the only way that makes sense in a broad context given the cascading nature of CSS (where you can have the same selector text as many times as you like).
However, my API keeps things in order so that every selector text is unique. Therefore, it makes sense to index the rules so that the main way of accessing them is via their selector text and my API does just that. However, things can quickly get less elegant when more than one level of rules are in play, i.e. if you have a number of media query rules containing their own index of CSS rules.
So I am just wondering if I can do anything to simplify the code and I must admit that were it not for the in this thread illustrated problems with hosted objects, i might have considered extending the CSSStyleSheet object.
Are there any other approaches, I might consider?