The way constructors are created
First, how do you create an object?
{key:value, key:value,… }, such as:
Var obj = {name: 'zhang3', age: 20, sex: 'male'}Copy the code
Note: This method can only create an object once, and the reuse is poor. If multiple objects are created, the code redundancy is too high
2. Use built-in constructors
var obj = new Object(); Name = 'obj '; obj.age = 22; obj.sayHello = function() { console.log("Hello!" )}Copy the code
3. Encapsulate simple factory functions
function createPerson() { var o = new Object(); o.name = name; o.age = age; o.sayHello = function() { console.log('Hello! ') } return o; //{name:"",age:"",sayHello:function... }} var obj = createPerson(' 5 ', 20); Var obj = createPerson(' createPerson ', 24);Copy the code
4. Custom constructors
- What is a constructor?
Constructors are functions, but they are usually used to initialize objects and are used with the new keyword.
-
New is used to create objects
-
Constructors are used to initialize objects (add members to objects)
-
Constructor name, uppercase!! Distinguished by the
Such as:
Function Person() {this.name = 'c '; this.age = 35; this.sayHello = function() { console.log('Hello! '); } //return; //return 123; //return {}; // Return {}, because {} is an object here} var p = new Person(); //new Object(); console.log(p); //Person{age: 35, name: 'sayHello ', sayHello: f()} p.sayhello (); // Hello!Copy the code
The execution of the constructor
1 Create an object using keyword new
Call the constructor and assign the newly created object to this
3 Use this in the constructor to add a member to the newly created object
4 Returns the newly created object by default (normal functions return undefined if no return statement is written)
The return value of the constructor
1 If you do not write the return value, the default return is the newly created object.
2 if you write a return statement, return is null (return;) , or a primitive type value, or null, returns the newly created object by default
3 If a value of type Object is returned, the newly created object will not be returned. Instead, the value following the return will be returned
Then create a constructor like this:
function Animal(name, type, barkWay) { this.name = name; this.type = type; This. Bark = barkWay} var dog = new Animal(' bark ', 'dog ', function() {console.log(' bark '); }); console.log(dog); } var cat = new Animal(function() {console.log(' meow meow meow '); }) console.log(cat); // bark: f(), name: 'bark ', type: The 'cat '} // object is an unordered collection of key-value pairs, so it prints bark,name,type, not name,type. The bark // array is ordered, so it prints what it definesCopy the code
Note: If you use the constructor as a normal function, this will no longer refer to the newly created object (because no object was created at all); When we use this to add members to the object, all members are added to the window, as in:
Animal('', '', function(){ console.log('I am Function! '); }); Bark (); // I am Function! A bark method has been added to the global object Window.Copy the code
Next, the problem with traditional constructors
The constructor
1. Identify the problem
Create a constructor like this:
function() { this.name = name; this.age = age; This.sayhi = function() {console.log(' Hello! '); }}Copy the code
Call this constructor to create an object and compare the sayHi method on the created object: sayHi
Var p = new Person(' Person ', 18); Var p1 = new Person(' Person ', 19); console.log(p.sayHi == p1.sayHi); // The output is falseCopy the code
Since each object is created by the new Person, the function sayHi is recreated for each object, and each object has a separate, identical method that does the same thing. There is no need to have so many copies in memory. So it’s a waste of resources.
2. Solve problems
The best thing to do here is to put the function body outside the constructor. You only need to reference the function in the constructor.
Function sayHello(){console.log(" hello "); } function Person(name, age){ this.name = name; this.age = age; this.sayHi = sayHello; } // call this constructor to create an object and compare the sayHi method of the object. Var p1 = new Person(" Person ", 19); console.log(p.sayHi == p1.sayHi); // The output is trueCopy the code
Note: There are problems with using this method
1 the number of global variables increases, causing pollution. 2 The code structure is chaotic and difficult to maintainCopy the code
3. The prototype
function Person(name,type) { this.name = name; this.type = type; This.sing = function() {console.log(' sing '); }; This.act = function() {console.log(' play action '); }} var p = new Person(' Person ', 'Person ');Copy the code
- What is the prototype?
When a constructor is created, by default the system creates and associates the constructor with a mysterious object, which is the prototype. The stereotype is an empty object by default
- The role of archetypes?
Properties and methods in the stereotype can be used by objects created using the constructor
- How do I access the constructor prototype?
Constructor. Prototype
console.log(Person.prototype); console.log(p.prototype); // undefined; Note that prooType is a constructor property and has nothing to do with the objectCopy the code
- How do I add properties and methods to a prototype object?
Use the dynamic nature of objects
Person. Prototype. act = function() {console.log(' play a play '); } p.act(); // Do action scenesCopy the code
Note: When using an object to access properties and methods, the object itself will be first searched, if found, directly use; If you can’t find it, look it up in the prototype. When you find it, use it. If it’s not in the prototype, if it’s a property, undefined; If it is a method, an error is reported.
p.dance(); //Uncaught TypeError: p.dance is not a function. TypeError: p.dance is not a functionCopy the code
4. Use prototypes to solve constructor problems
function Person() { this.name = name; this.age = age; this.sex = sex; SayHello = function() {// console.log(' Hello, I am '+ this.name); }} var p = new Person(' male', 18, 'male'); Var p1 = new Person(' male', 19, 'male'); Person. The prototype. SayHello = function () {the console. The log (' hello, my name is' + this. Name); } p.sayHello(); SayHell (); sayHell(); // Hello, THIS is Li SiCopy the code
- How can I use stereotypes to solve problems with constructors?
A member of the constructor’s prototype object, can be the constructor created all the object access, and all share the object, so we can will need to create a constructor function, on the prototype object storage, thus solve the problem of global variables, pollution, and the chaotic code structure.
Person. Prototype [' prototype '] = function() {console.log(' sun in the sky '); } p.sing(); P1.sing (); // The sun shines in the skyCopy the code
Common Mistakes
1. Write attributes inside (constructor. Prototype)
function Car(name){ this.name = name; } function Person() {} prototype.name = 'Person '; Person.prototype.car = new car (' Mercedes '); Var p = new Person();Copy the code
2. Assignment errors
Function Person() {} Person. Prototype. name = 'Person '; var p1 = new Person(); var p2 = new Person(); P1. Name = 'c '; console.log(p1.name); / / li si console. The log (p2) name); // If there is no data in the current object, go to the prototype property of the constructor. If the object does not have the data, add the valueCopy the code