wood burning stoves*
The moose likes HTML, CSS and JavaScript and the fly likes Using the new keyword in javascript Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Using the new keyword in javascript" Watch "Using the new keyword in javascript" New topic
Author

Using the new keyword in javascript

Rajesh Khan
Ranch Hand

Joined: Oct 16, 2011
Posts: 230
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

Joined: Jan 10, 2002
Posts: 60810
    
  65

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using the new keyword in javascript
 
Similar Threads
Javascript function isn't returning a value
javascript-AJAX regarding
call object per string
dojo loading FilteringTable problem
Javascript not detecting argument passed by JSP code