View Full Version : how does this work?

06-22-2005, 07:22 PM
Hi there!

I just wanna ask you how this function work or if there are document you can send me for reading that will be great. :)

if (!window.CSSStyleSheet){return}
var stylesheet = CSSStyleSheet.prototype;



This is the first time I have encountered this kind of function. You help is badly needed for me to have know about this function definition.

Thank you in advance!

06-22-2005, 10:21 PM
I just wanna ask you how this function workWhat you've posted doesn't really do much of anything.

The first thing to point out is that there is no function declaration in this code (this portion, at least). The pattern:

(function() {
/* ... */
})();is something I described (but didn't invent - just to make that clear) a while ago in this forum (http://www.dynamicdrive.com/forums/showthread.php?t=1666). It's generally used to isolate a portion of code so that variables created in it don't enter the global namespace, which can lead to conflicts.

(function() {
var local = 'a string';

function myFunction() {
/* ... */

/* Cannot access local here */In the code above, local is a local variable that can't be accessed outside of the containing function expression. However, local variables exist in the scope chain of inner functions.

A scope chain is a series of objects that contain a variety of properties, namely arguments, local variables, and function declarations. This chain is used to resolve identifier (variable) names. Nested functions like myFunction can use the chain to access the locals of its containing functions. In other words, code within myFunction could access local and any other local variables declared there.

if (!window.CSSStyleSheet){return}CSSStyleSheet is an interface defined by the W3C DOM Level 2 Style module (http://www.w3.org/TR/DOM-Level-2-Style). It is used to represent CSS style sheets as objects within a script so they can be manipulated at run-time. Some browsers will expose this interface directly, but most won't. This statement tests if the interface is accessible.

var stylesheet = CSSStyleSheet.prototype;This statement is more dubious than the last.

Whilst all native objects[1] in ECMAScript (JavaScript) have a prototype that defines what properties and methods are shared by all instances of that object, the same cannot be said of host objects (those provided by the host environment). This code will probably work on Mozilla (and the like) only.

What I expect is going to happen after this point is that the code will alter the prototype object, so that extra methods will be added to CSSStyleSheet objects.

Hope that helps,

[1] Native objects are those that are specified directly by ECMA-262. They are Object, Function, Array, Number, String, Boolean, Date, RegExp, and Error (and its derivatives).