The constructor is to initialize an instance object, and the prototype attribute of the object is to inherit an instance object.
Constructor Notes:
1. The first letter of the default function is capitalized
2. The constructor does not return anything. The new operator automatically creates the given types and returns them. When the constructor is called, new automatically creates the this object, and the type is the constructor type.
3. You can also call return explicitly in the constructor. If the returned value is an object, it will be returned instead of the newly created object instance. If the returned value is a primitive type, it is ignored and a newly created instance is returned.
function Person( name){ this.name =name; } var p1=new Person('John');
is equivalent to:
function person(name ){ Object obj =new Object(); obj.name =name; return obj; } var p1= person("John");
4. Because the constructor is also a function, it can be called directly, but its return value is undefined. At this time, the this object in the constructor is equal to the global this object. this.name actually creates a global variable name. In strict mode, an error occurs when you call the Person constructor via new.
5. You can also use the Object.defineProperty() method in the constructor to help us initialize:
function Person( name){ Object.defineProperty(this, "name"{ get :function(){ return name; }, set:function (newName){ name =newName; }, enumerable :true, //可枚举,默认为false configurable:true //可配置 }); } var p1=new Person('John');
6. Use prototype objects in the constructor
//比直接在构造函数中写的效率要高的多 Person.prototype.sayName= function(){ console.log(this.name); };
But if there are many methods, most people will adopt a simpler method: directly replace the prototype object with an object literal, as follows:
Person.prototype ={ sayName :function(){ console.log(this.name); }, toString :function(){ return "[Person "+ this.name+"]" ; } };
Rewriting the prototype object using literal form changes the properties of the constructor, so it points to Object instead of Person. This is because the prototype object has a constructor property, which other object instances do not have. When a function is created, its prototype property is also created, and the constructor property of the prototype object points to the function. When a prototype object is rewritten using object literal form, its constructor property will be set to a generic object Object. In order to avoid this, you need to manually reset the constructor when rewriting the prototype object, as follows:
Person.prototype ={ constructor :Person, sayName :function(){ console.log(this.name); }, toString :function(){ return "[Person "+ this.name+"]" ; } };
p1.constructor===Person