0
function Person1(name) {
    this.name = name;
}
function Person2(name) {
    this.name = name;
    return this.name;
}
function Person3(name) {
    this.name = name;
    return new Array();
}
function Person4(name) {
    this.name = name;
    return new String(name);
}
function Person5(name) {
    this.name = name;
    return function() {};
}


var person1 = new Person1('xl');  // {name: 'xl'}
var person2 = new Person2('xl');  // {name: 'xl'}
var person3 = new Person3('xl');  // []
var person4 = new Person4('xl');  // 'xl'
var person5 = new Person5('xl');  // function() {}

what has happened in new operator in javascript on earth? Especially the difference between person1 and person2.

X Rene
  • 419
  • 2
  • 7
  • before you ask anything on stackoverflow please try to search it on it http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Rahul May 17 '16 at 06:20

1 Answers1

0

The new operator creates a new instance of the Person function/class, you have to realize that function when using with the operator new is treated as classes like in any other language (c#,java, Python), so it creates a new context for the Person class, each context does not recognize other contexts of the Person object and it stands on its own,

In your example you created 5 different person functions which are equivalent for each other, instead you could simply create only 1 Person function and from him create 5 diferent instances

 var person1 = new Person('xl'); 
var person2 = new Person('xl'); 
var person3 = new Person('xl');  
var person4 = new Person('xl'); 
var person5 = new Person('xl')

// person1 != person2 
// person1.name == person2.name

Each person here is a different instance of the same class - Person.

When using a new operator you can use the reuturb statement inside the function, it doesn't mean abything, the return value of the new operator will the instance of the new object - therefore - the 'this' keyword inside the fubction, this is the context of the instance.

You could go in deeper with JavaScript classes and object inheritance in this link - https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

Ran Sasportas
  • 2,256
  • 1
  • 14
  • 21
  • Right??? There is a 'return' in every constructor... So the result is different. You can check it in the browser by using my code – X Rene May 17 '16 at 06:26
  • Even though , you shouldnt use a return statement with a new keyword, when using the new keyword the output for class should be the 'this' of the class instance – Ran Sasportas May 17 '16 at 06:32
  • well。I just want to know why the returned results are different. – X Rene May 17 '16 at 06:35