js basis - Constructor

What is the constructor?
In JavaScript, functions invoked with the new keyword, called the constructor.

Why use a constructor?
By generating object function

Mo classes of students to enter such personal information, create many objects

  var S1 = {name: 'John Doe', gender: 'M', age: 10, hobby: ' basketball' };
   var S2 = {name: 'John Doe', gender: 'F', age: 11, hobby : 'ballet' };
   var S3 = {name: 'Zhao before', Gender: 'F', age: 12, hobby: ' singing' };
   var S4 = {name: "Sun Wu ', Gender:' M ', age: 13, hobby: 'drifting' }; 
  ......

 

As too cumbersome to create an object, then you can use the build function. The same properties as constructor arguments. as follows:

function Student(name, gender,age, hobby) {
this.name = name;
this.gender = gender;
this.age = age;
this.hobby = hobby;
}

 

According to the constructor to create multiple objects, you must use the new keyword to call the constructor

var S1 = new new Student ( 'John Doe', 'M', 10 'basketball' );
 var S2 = new new Student ( 'John Doe', 'M', 11 'ballet' );
 var S3 = new new Student ( 'Zhao front', 'M', 12, 'singing' );
 var S4 = new new Student ( 'Sun Wu', 'M', 13 'drifting' ); 
the console.log (s1.name);

 

With the above example, the constructor visible code reuse may be implemented.

During the execution of the constructor
When a function is created, even if the function named capital, we can not be sure this is the constructor function.
A function to be called only if the new keyword can say it is a constructor.

When executed:  

       1. To invoke the new keyword to create a new memory space, marked instance of Student.
  2. The internal body of the function of this point [Example] The memory Student

And the difference between ordinary constructor function
  1. Create the same way, but the constructor capitalized
  2. The effect is not the same, the constructor to create an instance
  3. Call is not the same
  general function call: direct calls such as: person ()
  constructor calls : using the new keyword such as call: new Person ()

Guess you like

Origin www.cnblogs.com/lingXie/p/11574046.html