Inheritance and create js class

Class creation and inheritance

Create a class , new a function, in which the function of the prototype increase in properties and methods.

function A(food){

}

A.prototype.eat=function(food){
}

Prototype inheritance:

Student.prototype=new Person();
Student.prototype.constructor=Student;

Cons: Can not set the parameters of the constructor
to borrow constructors Inheritance:

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

var o={
name:'zs'
};
//bind方法 改变函数的this 并且返回一个新的函数 不调用函数
var f=fn.bind(o,1,2);
f();
//call函数 改变函数中的this 直接调用函数
fn.call(o.2.3);
		function Person(name,age,sex){
			this.name=name;
			this.age=age;
			this.sex=sex;
			
		}
		
		function Student(name,age,sex,score){
			Person.call(this,name,age,sex);//改变person的this 使其变成student 
			this.score=score;
			
		}
		
		var s1=new Student('zs',13,'男',100);
		console.dir(s1);

Cons: Only inheritable property, the method can not be inherited.

A combination of inheritance:
inherits methods and properties comprehensive:
a comprehensive method and call

Student.prototype=Person.prototype;
Student.prototype.constructor=Student;

But only one object point, that is one way to increase student, person also add a similar method. If you want only a certain subtype of the type of method and the parent is not, is a combination of the following:

Student.prototype=new Person();
Student.prototype.constructor=Student;
Published 158 original articles · won praise 44 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43277404/article/details/104322259