Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using the new keyword in javascript

 
Rajesh Khan
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi i was just working on my javascript and I was a bit confused on the use of the "new" keyword.

Consider the following example


Now in testing the code in firebug i realize i could call the function as
m.funct() --->A
although the above method does call the function but it also gives an output of undefined.Why does it give undefined.

Furthermore in other scripts i have seen functions such as above in maps being called as
var b = new m.funct();--->B

I wanted to know which is correct (A or B) and when should "new" be used.Because in most of java script code if i remove the new portion , the code doesnt work .
Why is that ??


 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65115
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajesh Khan wrote:although the above method does call the function but it also gives an output of undefined.Why does it give undefined.

The method returns nothing. So I don't see what you;d be surprised when it results in returning nothing. (undefined means nothing)

Furthermore in other scripts i have seen functions such as above in maps being called as
var b = new m.funct();--->B

That's actually kinda weird and I wouldn't emulate it.

Making a function a property of an object makes it a method of the object.

Using the new keyword to call a function calls it as a constructor. Making a single function be both a method and a constructor is not what I'd call a good practice.

I wanted to know which is correct (A or B) and when should "new" be used

Neither is always correct and neither is always incorrect. It all depends upon context and how the functions are defined and intended to be used.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic