LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Javascript object initialisation question (https://www.linuxquestions.org/questions/programming-9/javascript-object-initialisation-question-4175420873/)

resetreset 08-07-2012 01:58 PM

Javascript object initialisation question
 
If I say "new <function name>" to initialise an object, is the entire code for <function> RUN as part of the initialisation process?
What exactly happens?

Thanks.

dugan 08-07-2012 03:55 PM

<function>() is executed, with "this" set to a new object that inherits from the function's prototype.

And yes, I had to look that up.

resetreset 08-08-2012 08:25 AM

What does that mean? What if there IS nothing defined as a prototype? i.e. var x = new foo() ; is say, the first statement in the program, after the code for foo?

Also, someone (in the know, ostensibly) told me that the code for foo WON'T be executed - it'll only be compiled, and executed later....?

dugan 08-08-2012 08:52 AM

Quote:

Originally Posted by resetreset (Post 4748935)
What if there IS nothing defined as a prototype?

Then you can assume that "this" is {}.

This is probably the best information on the Javascript new keyword you can get for free:

https://developer.mozilla.org/en-US/.../Operators/new

You really should purchase a copy of "Javascript: The Good Parts", which is my go-to book for things like this: http://shop.oreilly.com/product/9780596517748.do

Quote:

Also, someone (in the know, ostensibly) told me that the code for foo WON'T be executed - it'll only be compiled, and executed later....?
I think there was a miscommunication involved. Foo is indeed executed, then its "this" is returned and assigned to x.

Yes, the entire code for the function is run when you call it with "new". I don't know why you or your friend would have thought otherwise.


All times are GMT -5. The time now is 05:54 PM.