Once again I found JavaScript code on the Internet that contains an inline function where, in my opinion, regular statements would make just as much sense. Here's the first sample:
function outerHTML(node){
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n) {
var div = document.createElement('div'), h;
div.appendChild(n.cloneNode(true));
h = div.innerHTML;
div = null;
return h;
})(node);
}
If you'd ask me to code the same thing, it would look like this:
function outerHTML(node){
var div, h;
// if IE, Chrome take the internal method otherwise build one
if (node.outerHTML) {
return node.outerHTML;
}
div = document.createElement('div')
div.appendChild(node.cloneNode(true));
h = div.innerHTML;
div = null;
return h;
}
EDIT: As OverZealous stated, there is a difference in logic on this one. I leave it here so nobody gets confused about that answer.
And maybe another original sample (yes, this doesn't "compile" as it's just a code fragment):
addGetters: function (attributes) {
var that = this;
function addGetter(attr) {
that.prototype["get" + attr.capitalize()] = function() { return this[attr]; };
}
for(var i = 0; i < attributes.length; i++) {
var attr = attributes[i];
addGetter(attr);
}
},
compared to my attempt
addGetters: function (attributes) {
for(var i = 0; i < attributes.length; i++) {
var attr = attributes[i];
this.prototype["get" + attr.capitalize()] = function() { return this[attr]; };
}
},
Is there a difference? Doesn't the original version consume more space since a function needs to be created and/or isn't it slower because of this? Is there a possible memory leak?
The utilisation of CPU and memory is very important as I'm coding in an environment where both are limited and any "less" is good. And since there's no sizeof() in JavaScript and its implementation attempts aren't safe to interpret any thinking-ahead-fixes are important.
Please note that as far as the "my version" is concerned I didn't test it. I'm just trying to explain what I'm trying to ask.
EDIT: Even though this question has an answer, I'm still wondering about the memory utilisation. If somebody has some insights, please don't hesitate to add it here.