21 : I can't really understand what is the use of new here!


#1


https://www.codecademy.com/courses/spencer-sandbox/3/2?curriculum_id=506324b3a7dffd00020bf661#


I can't understand what is the concept of writing new in ( var george =new Person ) so could anybody give a brief explanation ?


function Person(name,age) {
  this.name = name;
  this.age = age;
}

// Let's make bob and susan again, using our constructor
var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 25);
// help us make george, whose name is "George Washington" and age is 275
var george = new Person("George Washington",275)


#2

new is the special operator that invokes the constructor function to generate a new instance object. The resulting object has the direct properties declared in the constructor.as defined by the arguments passed to the function.


#3

Hello sir , Thanks alot for your fast response ! :slight_smile: , So we can say that new Person gives the variable the value of the Person method with empty valued parameters of (name,age) , right ?


#4

The constructor has two parameters so will be expecting two arguments. Since JavaScript is loosely typed the arguments may take any form, but they must be present or the script will raise an exception (fatal error).

In the above example we generated three instances of the Person class and assigned them to their respective variables, bob, susan and george. We may query these instances with property specific dot notation or by property index bracket notation.

console.log(bob.name);         // Bob Smith

console.log(susan.age);        // 25

console.log(george['name'])    // George Washington

Notice how each object has only the property values assigned when they were instantiated. There is a lot of work going on in the background that we do not see. It is thanks to new that we only get direct properties associated with the instance, not the entire this object, which is very verbose. That is why we do not write a return statement in a constructor function.


#5

Alright sir , i understand it now , thanks alot for your consideration :slight_smile:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.