I simply ran out of ideas why this piece of code works so strange,
it's a very simple class creating object:
var Class = function(tpl) {
return function() {
for(var t in tpl) this[t] = tpl[t];
};
}
var X = new Class({
arr: []
});
var x = new X;
x.arr.push(5);
var y = new X;
alert(y.arr[0]) // displays 5
How, I mean HOW in the world it displays 5? I tested it with normal
string and number variables - works fine, but I can't figure what's
wrong with the arrays? I tried to change the Class function in many
ways like making "new Object(tpl[t])" or "tpl[t].valueOf()" but
nothing helped.. I'm frustrated, it's so freakin strange..
Because you have created a very efficient memory leak over closure
with tpl value retained in it. I honestly have no idea what does this
code suppose to mean. Is it some work-on-denial test for a script
engine? There are more sophisticated professional packages for that,
Acid 3 from the first coming into my mind.
Maybe I should be more detailed. What you have originally posted is a
version of mutable anonymous constructor. This sick invention of some
Perl OOP traumatized programmer got in big fashion last year for some
reason: lucky by now this madness gets lesser and lesser popular. Do
do not be distracted by side issues, let's us take a mutable anonymous
constructor in its most simple form (comments are below the HTML):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en-US">
<head>
<meta http-equiv="Content-type"
content="text/html; charset=iso-8859-1">
<title>Demo</title>
<script type="text/javascript">
function Parent(outer_arg) {
return function(inner_arg) {
this['foo'] = outer_arg;
this['bar'] = inner_arg;
}
}
var Child = new Parent('foo');
var a = new Child('bar_a');
var b = new Child('bar_b');
var c = new Child('bar_c');
window.alert(a.foo==b.foo && b.foo==c.foo && c.foo=='foo'); // true
window.alert(a.bar); // 'bar_a'
window.alert(b.bar); // 'bar_b'
window.alert(c.bar); // 'bar_c'
</script>
</head>
<body>
<p>No content</p>
</body>
</html>
So what we have got here:
1) Parent creates Child and provides closure for Child. Grace to it on
each call Child has access to Parent context including outer_arg. This
is where in your sample the "mysterious" 5 value comes out.
2) Child constructor creates instances with per-instance properties.
Because Parent and Child are neither in class nor prototype
inheritance relations, I would say that 2007 was the year of birth of
all new "closure-based inheritance".
Once I tried to get an answer from one CS specialist what all these
mutable anonymous constructors - or closure-based inheritance or name
it as you want - is good for. With a light in he eyes he explained
that it allows to get all different instances from the same class
which are not in OOP relations with each other. Maybe I did not get
him right, or maybe he already got too much of Californian sun, or I
did, or both us. Any way.