[ES6]Day07 - constructor and prototype, inheritance

Getting started with ECMAScript 6 (Day07)

Continued: [ES6]Day06 - classes and objects in ES6

7.1.1 general

In the typical object-oriented language (java), there is the concept of class. Class is the template of object and object is the instance of class. But before ES6, js did not refer to the concept of class

There are three ways to create an object:

  1. Object Literal
   var obj={};
  1. new Object()
   var obj=new Object();
  1. Custom constructor

Extract the public part of the object and put it in the constructor. Create the object through the constructor

function Star(uname,age){
	this.uname=uname;
	this.age=age;
	this.sing=function(){
		console.log('I can sing')
	}
}
var hh = new Star('Jackson Yi',18); //establish hh object
var cc = new Star('Wang Yibo',21); // establish cc object
hh.sing();
cc.sing();

7.1.2 constructor

Constructor: a special function, mainly used to initialize objects, that is, to assign initial values to object members, always used with new. Extract the common properties and methods in the object, and then encapsulate them into the function.


7.1.2 static members and instance members

Static member: a member added by the constructor itself, which can only be accessed by the constructor itself
Instance member: the member added through this inside the constructor can only be accessed by the instantiated object

function Star(uname,age){
	this.uname=uname;
	this.age=age;
	this.sing=function(){
		console.log('I can sing')
	}
}
var hh=new  Star('Jackson Yi',18); //establish hh object 
hh.sing();
console.log(Star.uname);//undefined,Cannot pass constructor Star visit
console.log(hh.uname);//Jackson Yi,uname Is an instance member,Can only be accessed by instanced objects

Star.sex='male' //Static member
console.log(Star.sex) //male ,sex Is a static member,Constructor only Star To visit
console.log(hh.sex) // undefined

The instance members of the above code are: uname, age, sing, static member: sex

7.1.3 prototype of constructor

There is a problem with the constructor: every time an object is instantiated, a memory space will be created in memory, which is a waste of memory.

console.log(ldh.sing===zxy.sing)//false,The memory address is different, the method code is the same, and each memory space is occupied in memory, which is wasteful

How to save memory space by using the same function for all objects?

  • The functions assigned by the constructor through prototype are shared by all objects.

  • JS specifies that every constructor has a prototype property, which points to an object. Prototype is an object. All the properties and methods of this object will be owned by the constructor.


You can define invariant methods directly on prototype objects. In this way, instances of all objects can share these methods.

function Star(uname,age){
	this.uname=uname;
	this.age=age;
	//this.sing=function(){
	//	console.log('I can sing')
	//}
}
Star.prototype.sing =function(){
 	console.log('I can sing')
} 
var hh=new Star('Jackson Yi',18); //establish hh object 
var cc=new Star('Wang Yibo',21); // establish cc object
hh.sing();
cc.sing();
 


Question 1: what is the prototype?

Answer: prototype is an object in every constructor, so prototype is also called prototype object

Question 2: what is the role of prototypes?

Answer: using prototype allocation function can make all instances of objects share methods and save memory space.

Summary:

The public properties in the constructor are defined in the constructor, and the public methods are put on the prototype object of the constructor.

7.1.4 object prototype__ proto__

function Star(uname,age){
	this.uname=uname;
	this.age=age; 
}
Star.prototype.sing =function(){
 	console.log('I can sing')
} 
var hh=new Star('Jackson Yi',18); //There's a prototype on the object__proto__,Point to constructor Star Prototype object of prototype
hh.sing(); 

Why can instance objects hh and cc call sing() method in prototype object of Star without sing() method?

console.log(hh.__proto__===Star.prototype) //true,Object prototype__proto__And constructors Star Prototype object of prototype Is equivalent

Summary: objects all have one property__ proto__ The prototype object that points to the constructor is prototype. The reason why our object can use the properties and methods of the prototype object of the constructor is that the object has (two underscores)__ proto__ The existence of archetypes.

hh.sing(); 

Method search rule: first, check whether there is any on the hh object, and then execute sing() on the hh object,
If the object hh itself does not exist, go to__ proto__ Find the sing() method on the prototype object of the constructor pointed to.

7.1.5 constructor in prototype

Object prototype__ proto__ There is a property constructor in the prototype object of the constructor, which we call the constructor because it points to the constructor itself.


Constructor function: record which constructor the object refers to, and it can make the prototype object point back to the original constructor (Star).


be careful:

The second assignment below directly covers Star.prototype Object, so its constructor points to an object. If we modify the original prototype object and assign an object to the prototype object, we need to manually use the constructor to point to the original constructor.

  1. First, add the sing method to the prototype object of the constructor. The constructor points to the constructor Star
Star.prototype.sing =function(){
 	console.log('I can sing')
} 
  1. Second, assign an Object directly to the prototype Object. You need to manually use the constructor to point to the original constructor Star.
Star.prototype={ 
	constructor: Star,//Without this step, constructor Point to a Object
	
	sing: function(){
 		console.log('I can sing')
	}, 
	eat: function(){
 		console.log('I can eat')
	}
}  

7.1.6 relationship among constructor, instance and prototype object

1. Star constructor and prototype relationship
  • In each constructor, there is a prototype object, prototype, which is passed through the Star.prototype Pointing to a prototype object;
  • Prototype object prototype has a property called constructor, Star.prototype.constructor Pointer return constructor
2. Star constructor and instance object relationship
  • Create an instance object through the new constructor
3. Prototype relationship between instance object and prototype object
  • As long as it's the object__ proto__ Prototype refers to the prototype object prototype of the constructor, which is unique to the object.
  • Of instance objects__ proto__ There is a property constructor in the prototype through the prototype object Star.prototype Point to star constructor

7.1.7 prototype chain (key)

function Star(uname,age){
	this.uname=uname;
	this.age=age; 
}
Star.prototype.sing =function(){
 	console.log('I can sing')
} 
var hh=new Star('Jackson Yi',18); //There's a prototype on the object__proto__,Point to constructor Star Prototype object of prototype

hh.sing()

console.log(Star.prototype.__proto__===Object.prototype);//true
console.log(Object.prototype.__proto__===null);//true

1. As long as it's the object__ proto__ Prototype, pointing to prototype object

2. In prototype object of constructor star__ proto__ Archetype( Star.prototype H. proto__) Point to object prototype object( Object.prototype )

3. Object constructor creates prototype object( Object.prototype ), object prototype object.constructor( Object.prototype.constructor )Point to object constructor

4, Object.prototype In the prototype object__ proto__ Prototype points to null


We found that every object has__ proto__ Prototypes__ proto__ The prototype also points to the prototype object, forming a prototype chain. When you search for member variables, you will find them layer by layer. If you can't find them all, you will see null

Summary: JavaScript lookup member mechanism (rules)

Question 1: what is a prototype?

Answer: prototype is an object in every constructor, so prototype is also called prototype object

Question 2: what is the role of prototypes?

Answer: using prototype allocation function can make all instances of objects share methods and save memory space.

Question 3: what is a prototype chain?

  • Each object can have a prototype_ proto_ This prototype can also have its own prototype, and so on, forming a prototype chain.
  • When searching for a specific attribute, we first go to the object, if not, go to its prototype object, if not, then go to the prototype object of the prototype object This operation is entrusted to the whole prototype chain, which is what we call the prototype chain.

7.1.8 prototype object this point

function Star(uname,age){
	this.uname=uname;
	this.age=age; 
}
var that;
Star.prototype.sing =function(){
 	console.log('I can sing')
 	that=this;
} 
var hh=new Star('Jackson Yi',18);   
hh.sing();
console.log(that===hh) //true

1. In the constructor, this refers to the instance object hh

2. this in the prototype object function refers to the function caller. Here is the instance object hh

7.1.9 extending built-in objects

You can expand the custom methods for the original built-in objects through the prototype objects, such as adding the custom even sum function to the array

Array.prototype.sum=function(){
	var sum=0;
	for(let i = 0; i < this.length ; i++){
		sum+=this[i];
	}
	return sum;
}

var arr=new Array(1,2,3)
arr.sum() //6

//Printing Array.prototype 

Don't add the method in the following way, which will overwrite the original method of the prototype. The constructor point is also different

// Array.prototype={
//	sum:function(){
//		var sum=0;
//		for(let i = 0; i < this.length ; i++){
//			sum+=this[i];
//		}
//		return sum;
//	}
//}

7.1.10 combination inheritance

ES6 did not provide extensions inheritance before. We can implement inheritance through constructor + prototype object simulation, which is called combinatorial inheritance

1,call()

Syntax: func.call(thisArg, arg1, arg2, ...argN)

parameter meaning
thisArg Object of this
arg1, arg2, ...argN The parameters that need to be passed in to call func functions are all separated by commas and placed directly after them

Function: call func function, and change this point of function runtime

example:

function fn(x,y){
	console.log(this);
	console.log(x+y);
}

var o={
	name:'sam'
}
fn.call(o,3,8) 

2,bind()

Syntax: let boundfunc= func.bind (thisArg, arg1, arg2, ...argN)

parameter meaning
thisArg Object of this
arg1, arg2, ...argN To call a func function, you need to separate all the parameters passed in with commas, put them directly behind, and return a function (closure). The function is delayed to execute and needs to be called to execute

Function: when we call some functions, we can only call them in a specific environment, so if we use bind() to bind the functions to a specific environment

example:

function fn(x,y){
	console.log(this);
	console.log(x+y);
}

var o={
	name:'sam'
}
fn.bind(o,3,8)  // output fn Function, will not execute
fn.bind(o,3,8)() //implement fn Function, output {name:'sam'}  11 

3,apply()

Syntax: func.apply(thisArg, [argsArray])

parameter meaning
thisArg Required. This value used when func function runs. Note that this may not be the actual value seen by the method: if this function is in non strict mode, when it is specified as null or undefined, it will be automatically replaced by pointing to the global object, and the original value will be wrapped.
argsArray Optional. An array or class array object in which the array elements are passed as separate parameters to the func function. If the value of the parameter is null or undefined, no parameter needs to be passed in. Starting with ECMAScript 5, you can use class array objects.

Function: the apply() method calls a function with the given this value and the parameters provided as an array (or similar array object).

example:

function fn(x,y){
	console.log(this);
	console.log(x+y);
} 
var o={
	name:'sam'
}
fn.apply(o,[3,8])  //output {name:'sam'}  11 
fn.apply(o,3,8)    //report errors ,Because the second argument is not an array or a class array

4. The difference between call(), bind(), and apply():
var obj={
    name:'Zhang San',
    age:18,
    myFun:function(fm,to){
        console.log(this.name+" Age"+this.age,fm + "Go to" + to);
    }  
}
var db={
    name:'Dema',
    age:99
}

obj.myFun.call(db,'Chengdu','Shanghai');   //Dema Age99 Chengdu to Shanghai

obj.myFun.apply(db,['Chengdu','Shanghai']);   //Dema Age99 Chengdu to Shanghai  

obj.myFun.bind(db,'Chengdu','Shanghai'); // Return a function, here is bind and call/apply One of the differences, bind Not immediately

obj.myFun.bind(db,'Chengdu','Shanghai')();    //Dema Age99 Chengdu to Shanghai

obj.myFun.bind(db,['Chengdu','Shanghai'])();  //Dema Age99 Chengdu,Shanghai to undefined

Similarities

1. The first parameter of these three functions is the pointing object of this
2. The parameters of the three are not limited to string type, but can be of various types, including function and object

difference

The second parameter is different:

1. The second to nth parameters of call() are all separated by commas and placed directly after obj.myFun.call(db, 'Chengdu',...,'string ');

2. All parameters of apply() must be passed in an array obj.myFun.apply(db, ['chengdu ',...,'string'];

3. bind() has the same parameters as call() except that it returns a function.
    
4. call() and apply() are directly used on functions, and bind returns functions (closures) whose execution context has been changed after binding this. They will not be executed immediately, and need to be executed.

Array.prototype.sum=function(){
	var sum=0;
	for(let i = 0; i < this.length ; i++){
		sum+=this[i];
	}
	return sum;
}

var arr=new Array(1,2,3)
arr.sum() //6

//Printing Array.prototype 
5. Borrow constructor to inherit parent type property

Core principle: call() to point this of the parent type to this of the child type, so that the child type inherits the properties of the parent type.

function Father(uname,age){,
	//this Point to parent constructor Object instance of
	this.name=uname;
	this.age=age;
}

function Son(uname,age,score){
	//this point Child constructor Object instance of
	Father.call(this,uname,age) //change this point 
	this.score=score; //Son has his own attributes
}
var son =new Son('Jackson Yi',25)
console.log(son) 
6. Borrow prototype object inheritance method
function Father(uname,age){
	//this Point to parent constructor Object instance of
	this.name=uname;
	this.age=age;
}
Father.prototype.money=function(){
	console.log("1000 element") 
}
 
function Son(uname,age,score){
	//this point Child constructor Object instance of
	Father.call(this,uname,age) //change this point 
	this.score=score; //Son has his own attributes
}

// Son.prototype=Father.prototype //You can't assign directly this way, if you modify the sub prototype object (add exam Method), the parent prototype object will also change 
 
Son.prototype=new Father();  //amount to= New objects {}
// If using object form to modify Prototype object, don't forget to use constructor Gyrus digiti Original constructor
Son.prototype.constructor = Son; //If you don't come back, Son.prototype.constructor It points to Father Constructor.

Son.prototype.exam=function(){
	console.log("Only a bad child can have an exam!");
}
var son =new Son('Jackson Yi',18,100)
console.log(son) 
console.log(Father.prototype)

The first: Son.prototype=Father.prototype

If the child prototype object is modified (add the exam method), the parent prototype object will also be changed (the Father also adds the exam), so it cannot be assigned directly

Second:

 Son.prototype=new Father() 
 Son.prototype.constructor = Son;     

1. By creating a parent instance object and making the child prototype object point to the parent instance object, the money method inheriting the parent constructor is implemented. At the same time, modifying the child prototype object (adding the exam method) will not directly modify the parent prototype object, but also create a method belonging to the child constructor

2. If the prototype object is modified in the form of an object, and the constructor is used to refer back to the original constructor (Son constructor), if not, the following will appear:

Reference link:

Ruan Yifeng: introduction to ECMAScript 6

Tags: ECMAScript Java Javascript Attribute

Posted on Wed, 17 Jun 2020 21:44:52 -0400 by Axem