I have been severely bitten by Javascript's closures bug a few days ago, but was too busy to ask. I am trying something like the following with the jQuery template engine.
<ul id="container"></ul>
<script type="text/jq-tmpl" id="myTmpl">
<li>
<span style="background:#fafafa">X:${X}</span>
<span style="background:#ababab">Y:${Inner.Y}</span>
<span style="background:#9a9a9a">Z:${Inner.Z}</span>
</li>
</script>
function OuterObject(x,y,z){
this.X = x;
this.Inner = InnerObject(y,z);
}
function InnerObject(y,z){
this.Y=y;
this.Z=z;
}
$(function(){
var l=[];
l.push(OuterObject(1,"One","inner-1"));
l.push(OuterObject(2,"Two","inner-2"));
$("#myTmpl").tmpl(l).appendTo("#container");
});
The problem is that it shows inner-2 and Two for both the items rendered. I have also tried it like this:
var a=OuterObject(1,"One","inner-1");
l.push(a);
var b=OuterObject(2,"Two","inner-2");
l.push(b);
But is all the same.
1 Answer 1
It looks like you need to use 'new' when calling your constructor functions.
e.g. new Outerobject(...) and new InnerObject(...)
Otherwise, the this object won't be returned.
Sign up to request clarification or add additional context in comments.
4 Comments
mu is too short
And
this inside the functions will be window.amantur
@muistooshort don't tell me. It is from here w3schools.com/js/js_objects.asp (2. Create an object constructor). Then what is recommended to use in functions instead of
this?mu is too short
amantur
@muistooshort so if I use
var x=new InnerObject() the this refers to current scope, else it refers to window. thanks dear. this is really an eye opener.Explore related questions
See similar questions with these tags.
lang-js