1

Here is a function:

function ShowHelloWorld(){
 this.x=4;
 var y=5;
 return 6;
}

Statement 1. var res1 = ShowHelloWorld;

1.1 So, res1 is a copy of ShowHelloWorld function.

1.2 res1() gets 6.

1.3 There is no way to reach values 4 and 5 from res1.

Statement 2. var res2 = ShowHelloWorld();

2.1 res2 gets 6 as a result of a function.

2.2 There is no way to reach values 4 and 5 from res2.

Statement 3. var res3 = new ShowHelloWorld();

3.1 Here res3 is an instance of the function ShowHelloWorld().

3.2 res3.x can be reached. //res3.x==4

3.3 There is no way to reach values 5 and 6 from res3.

Statement 4. var res4 = new ShowHelloWorld; // with no ()

4.1 Seems like res4 is the same res3. Why? (I see it is the same when I test it in the browser console).

4.2 What's the sense of this line (it makes sense if it has no errors, right?)

Please answer my questions or correct my statements in case if they are incorrect or could be even better.

Thank you.

1
  • 1
    1.1 and 3.1 are wrong. 3.2 is wrong because of a typo. 4.2 does not return a boolean. Commented Feb 28, 2014 at 10:14

2 Answers 2

2

1) res1 is not a copy of ShowHelloWorld. It's just a reference, an alias.

2) res2 is a result of calling ShowHelloWorld. The rest is true.

3) Somewhat true. However if you return an object (6 is a primitive, not an object), then new will return that object. Have a look at this snippet:

function ShowHelloWorld(){
  this.x=4;
  var y=5;
  return {};
}

Now nothing is accessible except for the final object {}. So if you want to treat a function as a class (i.e. you want to use new on it) then it is a good practice to omit the return statement.

4) new ShowHelloWorld; is just an alias for new ShowHelloWorld();

Sign up to request clarification or add additional context in comments.

Comments

1

Statement 4 is equivalent of Statement 3 because of javascript syntax. After 'new' keyword should be name of function that will be used as constructor. Params can be skipped.

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.