Re: Very strange problem with Class object
- From: "Richard Cornford" <Richard@xxxxxxxxxxxxxxxxxxx>
- Date: Mon, 31 Mar 2008 01:31:16 +0100
Piotr K wrote:
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?
You assign a reference to an array to its 'arr' property when your
create your - x - object and then assign a reference to the same array
to the 'arr' property of your - y - object when your create that. Then
when you push an element onto that array it is a member of the array
referred to as - x.arr - and - y.arr -.
I tested it with normal
string and number variables - works fine,
Using - push - on an array is modifying that array. There are no
operations in javascript that are capable of modifying a primitive
value, so you could not be doing the equivalent to a string or a number.
but I can't figure what's wrong with the arrays?
What is wrong is that you are expecting each object instance to have its
own array instance but you have programmed them to share a single array
instance.
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..
function X(){
this.arr = [];
}
var x = new X;
x.arr.push(5);
var y = new X;
alert(y.arr[0]) // displays undefined
Don't over-complicate things.
Thanks for any help!
It is best to disregard anything that VK says as he has no idea what his
own cod actually does let alone anyone else's. Earlier in the week he
posted:-
| <script type="text/javascript">
| (function(){
| var name = 'doc02';
| document.write(''.concat(
| '<iframe name="',name,'" ',
| 'src="',getUrlForIframe(name),'" ',
| 'onload="',
| '(function(){',
| 'var n = \'',name,'\';',
| 'var win = self.frames[n];',
| 'var doc = win.document;',
| 'if ((doc) && (\'designMode\' in doc)) {',
| ' doc.designMode = \'on\';',
| '}','})();"'));
| window.alert('Fine up to this point');
| })();
| window.alert('getUrlForIframe is ' + typeof getUrlForIframe);
| window.setTimeout('window.alert(true)',1000);
| </script>
- which is insane, and if you asked him to explain that - onload -
attribute he either could not or would post a nonsense explanation.
Richard.
.
- References:
- Very strange problem with Class object
- From: Piotr K
- Very strange problem with Class object
- Prev by Date: IE and Enter (multi-Input form)
- Next by Date: Re: Strange problems with JSON and Safari
- Previous by thread: Re: Very strange problem with Class object
- Next by thread: Strange problems with JSON and Safari
- Index(es):
Relevant Pages
|