When to use the constructor, the constructor with the new keyword

Js on when to use a constructor 
    generally have the same attributes create multiple objects / methods, will go write constructor will go new
     if only a single object, literals directly on the line 

var Person = { 
    name: 'postbird' , 
    address: 'Earth' , 
    the sayHello: function () {the console.log ( 'the Hello, the I AM' + the this .name);} 
};
js constructor creates objects add new questions 

/ * 
    new operators have done it: 
      1. Create a new object 
      2, the scope constructor assigns the new object (and therefore this points to the new object) 
      3, execution constructor code (added for the new object attribute) 
      4, returns a new object. 
* / 

Function the Obj (name) {
     the this .name = name;     
    the console.log ( the this ); // strict mode is a mode undefined nonstrict window object 
}
 var A = the Obj ( "name11"); // undefined 
A .name; // Uncaught TypeError: Can Not Read Property 'name' of undefined 
var B = new new the Obj ( 'name22');   // the Obj {name: "name22"} 
b.name; //name22 


// the new operator to create an object, and a constructor or no return value returned as basic data types, the object is returned 
function the Obj (name) {
     the this .name = name; 
} 
var B = new the Obj (); // {name obj: undefined} 

function obj (name) {
     the this .name = name;
     return 'Chic' ; 
} 
var B = new obj (); // obj {name: undefined} 

// create an object with the new operator, and constructor returns a reference type 
function Obj02 (name) {
     the this .name = name;
     return {}; 
}
var A02 = Obj02 ( "name11"); // Object {} 
a02.name; // undefined 
var B02 = new new Obj02 ( 'name22');   // Object {} 
b02.name; // undefined 

/ * * 
 * summarized : 
 * to be executed without new constructor, the return value is the result of the implementation of the constructor 
 * to add new keywords to the constructor in terms of execution, if the return is a basic data type, overlooked the return value, 
 * for the purposes of adding new keywords to the implementation of the constructor, if the return is a reference type, then returned to the reference type 
 * /
 
 

 


If you have a lot of object instances, inheritance or directed or mass participation constructor 

function the Person (name, address) {
     the this .name = name;
     the this .Address = address; 
} 
Person.prototype.sayHello = function () { 
    the console.log ( 'the I AM the Hi' + the this .name); 
} 

var P1 = new new the Person ( 'postbird', 'Earth' );
 var P2 = new new the Person ( 'ptbird', 'month The' ); 
In general, the constructor used widely, if simply objects, use literal enough. 

In the constructor object instantiation, inheritance and other applications, or more

 

Guess you like

Origin www.cnblogs.com/slightFly/p/11441122.html