Skip to main content

Using "return" when creating objects with "new"


I found something very odd today: If you create objects with a constructor function and the new keyword, but return a function from the constructor, it behaves like so:



  1. The newly-created "object" is instead a function.

  2. That new function can be invoked like normal, however...

  3. If you maintain a reference to this in the constructor function, this references an object that was correctly created from the constructor. It's what you expected to be returned from new .



Here's an example:




function Constructor() {
var self = this;

this.name = 'instance';
return function() {
return self;
}
}



So if you instantiated it like this: var instance = new Constructor() The following would result:




typeof instance //returns "function"
typeof instance() //returns "object"
instance() //returns { name: 'instance' }



So I guess I have three questions:



  1. Is this legal and does it work cross-browser? It's really awesome and I think it can be used in a lot of ways, but is this behavior dependable?

  2. What happens in the background that causes this behavior?

  3. (maybe answered by 2, but...) Is the new object (the one referenced with 'this') inside the new instance, so that it's all self-contained and is cleaned up properly by the garbage collector?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. Well, that is a really good question and, as you may have guessed, not easily answered.

    To put it very simply:
    1) Yes and Yes; this is one of the amazing features you don't find in "traditional" programming languages.
    2) please read about closures (links below)
    3) Yes (please read more)

    You should read more about Javascript Closures:
    http://jibbering.com/faq/notes/closures/
    http://www.javascriptkit.com/javatutors/closures.shtml (here you got some good working examples)

    and, more particularly, the Parasitic Inheritance model:
    http://blog.higher-order.net/2008/02/21/javascript-parasitic-inheritance-power-constructors-and-instanceof/

    I hope this helps

    ReplyDelete
  2. this is what you call a closure

    what it does is create a self-contained code environment (commonly known as an object)

    typeof instance //returns "function" - since it's not "fired" or called. just returns the function declaration (correct me if i'm wrong)
    typeof instance() //returns "object" - it returns an object since you called it
    instance() //returns an object also - you called it, but you didn't store it


    an example of an object built using a closure:

    function Constructor() {
    var privateProperty = 'private';
    var privateMethod = function(){
    alert('called from public method');
    };

    //return only what's to be seen in public
    return {
    publicProperty: 'im public',
    publicMethod: function(){
    alert('called from public method');
    }
    getter: privateMethod //assign to call the private method
    }
    }

    var myObj = Constructor();
    var pubProp = myObj.publicProperty; // pubProp = 'im public'
    myObj.publicMethod() //alert: 'called from public method';
    myObj.getter() //alert: 'called from public method';

    //cannot access since "private":
    myObj.privateProperty
    myObj.privateMethod

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.