0

I am newbie to javascript and oops. I have a javascript function

function foo(args){

   ...
}


//mehtod1
var type1=foo(a);

//mehtod2
var type2= new foo(a);

Now my doubt is which will give us more performance mehtod1 or method2

what is the significance of new keyword and what are the advantages over mehtod1?

(sorry if the question already exists and for my poor english)

2 Answers 2

5

The first call performs one operation: function evaluation. The second performs two: creates a new object and then does a function evaluation. Don't use new to evaluate a function.

Here is an example:

var x = function () { return true; };

var y = x(); // Type of y is boolean
var y = new x; // Type of y is object
var y = new x(); // Type of y is object
var y = x; // Type of y is a function
var y = x.call(this); // Type of y is a boolean
Sign up to request clarification or add additional context in comments.

1 Comment

@icktoofay thank you for correcting me, you're absolutely right. I will edit in just a second
1

They are different.

type1 will be the return value of function foo.

type2 will be an object whose constructor is function foo.

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Reference.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.