Prototype chain various inheritance methods

*Prototype chain inheritance:
1. Define the supertype constructor
2. Add a method to the prototype of the parent type
3. Define the constructor of the subtype
4. Create the object of the parent type and assign it to the prototype of
the subtype 5. Construct the prototype of the subtype Set the property to the subtype
6. Add a method to the subtype prototype
7. Create an object of the subtype: You can call the method of the supertype
*Key:
1. The prototype of the subtype is an instance object of the supertype

            function Super(){
    
    
				this.SuperPro = "SuperPro";
			}
			Super.prototype.showSuper = function(){
    
    
				console.log(this.SuperPro);
			}
			function Sub(){
    
    
				this.SubPro = "SubPro";
			}
			Sub.prototype.showSub = function(){
    
    
				console.log(this.SubPro);
			}
			//让子类型的原型成为父类型的原型的属性
		    	Sub.prototype = new Super();
		    //让子类型的原型的constructor指向子类型,不实现此举,则Sub的构造函数是Super()
		       Sub.constructor = Sub;
			var son = new Sub();
			   son.showSuper();   //SuperPro
			var senior = new Super();
			   senior.showSuper();  //SuperPro

// Borrowing constructor inheritance (false, no inheritance, simplifies the code)
*define the supertype constructor
*define the subtype constructor
*call super() in the subtype constructor to call the supertype constructor

           function Person(name , age){
    
    
 				this.name = name ;
				this.age = age; 
			}
			function Student(name , age , price){
    
    
				Person.call (this,name,age);   
				//相当于: this.Person(name,age);
				// this.name = name ;
				// this.age = age ;
				this.price = price;
			}
			  var s = new Student("Vodka",20,10000);
			  console.log(s.age,s.name ,s.price);  //20,Vodka 10000

// Combination inheritance of prototype chain + borrowed constructor
// *Using prototype chain to implement method inheritance
of super- type objects // *Using super() to borrow super-type construction function to initialize the same properties

            function Person(name ,age ){
    
    
				this.name = name ;
				this.age = age ;
			}
			function Student(name , age , price){
    
    
				Person.call(this,name,age);  //使子类成为父类构造函数的调用对象,给子类添加属性
				this.price = price;
			}
			//使子类的原型对象成为父类的一个实例对象,这样子类就可以访问父类原型对象中的属性和方法
			    Student.prototype = new Person();
		    //修正Student的构造函数的指向,让它指向Student,而不是Person
			    Student.prototype.constructor = Student;
			Person.prototype.setName = function(name){
    
    
				this.name = name ;
			}
			Student.prototype.setPrice = function(price){
    
    
				this.price = price ;
			}
			var s  = new Student("James",98,999); //James 98 999
			console.log(s.name,s.age,s.price);  //name和age所属对象是Person,price的所属对象属于Student
			s.setName("Vodka");  //该方法所属对象是Person.prototype
			s.setPrice(8989);  //该方法所属对象是Function.prototype
			console.log(s.name,s.age,s.price); //Vodka 98 8989

Guess you like

Origin blog.csdn.net/Vodka688/article/details/113748045