js类的继承与创建

类的创建和继承

类的创建,new 一个function ,在这个function的prototype里面增加属性和方法。

function A(food){

}

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

原型继承:

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

缺点:无法设置构造函数的参数
借用构造函数继承:

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);

缺点:只可继承属性,不能继承方法。

组合继承:
继承方法与属性综合:
综合call方法和

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

但只有一个对象指向,即student增加一个方法,person也增加一个同样的方法。若想子类型只有某个方法而父类型没有,则结合以下:

Student.prototype=new Person();
Student.prototype.constructor=Student;
发布了158 篇原创文章 · 获赞 44 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43277404/article/details/104322259