3

There are two functions here.

1) created with 'new' object.

( function se(){ var a=10; var t = function (){ var that=this; alert(a); that.book= function (){ alert(that); } that.book(); } return new t(); }() ); 

2) With object literal way

( function se(){ var a=10; var f={ init:function(){ alert(a); } } f.init(); }() ); 

So what is the best practice to use? and why? What is the purpose of using 'this' in the 1st example?

5
  • The functions aren't self-invoking, which implies recursion Commented Jun 8, 2012 at 6:19
  • @Esailija: you could say the se functions are self-invoking here. Commented Jun 8, 2012 at 6:22
  • 1
    Best practice is neither option. Both create an object that is not stored anywhere so the net effect is to display two alerts (first option) or a single alert (second option). @haylem: they're not self-invoking - the function body does not recursively call the function. They're "immediately invoked function expressions". Commented Jun 8, 2012 at 6:24
  • @nnnnnn: "could say" as in "you can understand that the OP would call them that" and not know "immediately invoked function expressions". Commented Jun 8, 2012 at 6:52
  • 'this' in the 1st example is a "link" to an object that WILL BE created by calling new t() Commented Jun 8, 2012 at 10:04

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.