A
A
albertineo2017-05-07 22:46:38
JavaScript
albertineo, 2017-05-07 22:46:38

Are private constructor properties copied during new object creation in JavaScript?

In this example, how is it that each object created using the User constructor has its own variables firstName, surname.

function User() {

  var firstName, surname;

  this.setFirstName = function(newFirstName) {
    firstName = newFirstName;
  };

  this.setSurname = function(newSurname) {
    surname = newSurname;
  };

  this.getFullName = function() {
    return firstName + ' ' + surname;
  }
}

var user = new User();
var user2 = new User();

user.setFirstName("Петя");
user.setSurname("Иванов");

user2.setFirstName("Петя222");
user2.setSurname("Иванов222");
alert( user.getFullName() );
alert( user2.getFullName() );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dark Hole, 2017-05-07
@abyrkov

Nope. Each call creates new functions setFirstName , setSurname , getFullName , which receive new closure variables firstName , surname .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question