0

I have written following code and it is not showing any alert.

var test = function(message) {
    this.show = function() {
        alert(message)
    }
}
(new test("hiii")).show();
(new test("helooo")).show();

When changed to following... Removed the bracket of - (new test("hiii")).show();

It shows both "hiii" and "helooo" alert.

Note: I did not make any changes to - (new test("helooo")).show();

var test = function(message) {
    this.show = function() {
        alert(message)
    }
}
new test("hiii").show(); // was(new test("hiii")).show();
(new test("helooo")).show();

Can anyone explain why?

5
  • Both solutions work fine for me. Commented Jul 14, 2015 at 12:41
  • @zerkms I copied that first block of code into the Firefox debug console and it got an error. Commented Jul 14, 2015 at 12:43
  • @zerkms - you added the semicolon!! Commented Jul 14, 2015 at 12:43
  • 3
    No, the semicolon wasn't in the original. @Tushar added the semicolon which I removed. Commented Jul 14, 2015 at 12:44
  • @BibinVenugopal it was not in the very initial revision of the question Commented Jul 14, 2015 at 12:45

2 Answers 2

3

The problem, oddly enough, is with the fact that you left out the semicolon after your function expression:

var test = function(message){
    this.show = function() {
            alert(message)
    }
} // <-- missing semicolon

That means that the ( ... ) following the function expression is taken to be the argument list for a function call.

Add that missing semicolon and the first block of code will work.

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

Comments

0

Since semicolon is missing it will take as self invoking function expression with argument new test("hiii") so use it like this

var test = function(message) {
   this.show = function() {
       alert(message)
 }
};
(new test("hiii")).show();
(new test("helooo")).show();

Comments

Your Answer

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