JavaScript tricks
The more I use JavaScript, the more I like it. It's really a powerful language. It's almost Lisp without the parentheses.
I often stumble on new tricks... Here are two I stumbled upon today. Local variablesTake note that JavaScript is very dynamic and there isn't a smart optimizer to improve your code. To create optimized JavaScript it's very wise to use local variables, the main reasons are:
Today I have written following: this.iframe = AJS.IFRAME();
var iframe = this.iframe;
The above code can be written like this: var iframe = this.iframe = AJS.IFRAME();
JavaScript is dynamicJavaScript is dynamic and almost everything is an object - with this in mind you can create some beautiful JavaScript. I have written following "common" JavaScript: iframe.style.height = tr_main.offsetHeight + toolbar_height + 'px';
iframe.style.top = toolbar_height+2 + 'px';
iframe.style.left = toolbar_left+2 + 'px';
It can be written into something more readable (DRY): AJS.update(iframe.style, {
height: tr_main.offsetHeight + toolbar_height + 'px',
top: toolbar_height+2 + 'px',
left: toolbar_left+2 + 'px'
});
Or like this: var dims = {
height: tr_main.offsetHeight + toolbar_height + 'px',
top: toolbar_height+2 + 'px',
left: toolbar_left+2 + 'px'
}
for(key in dims)
iframe.style[key] = dims[key];
I of course like the AJS.update version better :)
Code
·
Code improvement
·
JavaScript
·
Tips
•
22. Mar 2007
|
|