0

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.

dda
6,2212 gold badges27 silver badges37 bronze badges
asked Jul 19, 2012 at 4:53

1 Answer 1

2

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.

answered Jul 19, 2012 at 5:01
Sign up to request clarification or add additional context in comments.

4 Comments

And this inside the functions will be window.
@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?
@TheVillageIdiot: (1) Don't trust w3fools (2) this will be window unless you use new.
@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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.