What is the purpose of these two different javascript declarations?

I think it turned out, but I hope it will be clear - what exactly is the difference between these two javascript fragments?

;Person1 = (function() {
  var FirstName = 'Hello';
  var LastName = 'World';
  this.sayHello = function() {
    alert(FirstName + ' ' + LastName);
  };
});

;Person2 = (function() {
  var FirstName = 'Hello';
  var LastName = 'World';
  this.sayHello = function() {
    alert(FirstName + ' ' + LastName);
  };
})();

One is done using (); in the end, there is no other. They execute as expected when I do a new Person1 (). SayHello () or the new Person2 (). SayHello (); - is that what they leave? From what I understand, the latter is the closure that the browser performs, HOW IT IS READ, but I have not yet fully understood the consequences of this. Thank you for your help!

UPDATE: I mistakenly left the return keyword in closing Person2. However, I did not fix it because the answers were very helpful in describing the consequences of this :)

+3
source share
3

Person1 , new. new Person1() sayHello.

Person2 , ! Person2, ( ). this window. , Person2 undefined:

>>> Person2 = (function() { var FirstName = 'Hello' // ...}; })(); 
>>> console.log(window.sayHello, Person2);
function() undefined

A new Person2() , TypeError "Person2 ". , Person2 :

;Person2 = (function() {
  var FirstName = 'Hello';
  var LastName = 'World';
  return {
    sayHello: function() {
      alert(FirstName + ' ' + LastName);
    }
  };
})();

Person2.sayHello();

( new Person2()):

;Person2 = (function() {
  var FirstName = 'Hello';
  var LastName = 'World';
  return function() {
    this.sayHello = function() {
      alert(FirstName + ' ' + LastName);
    };
  };
})();
0

inline Person1 .

, . inline . , Person2 undefined.

no example behaves the way you describe, so maybe you made a mistake typing your example?

0
source

Source: https://habr.com/ru/post/1745121/


All Articles