js中对象继承
1.js原型(prototype)实现继承,所谓的原型链继承
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayHello=function(){
alert("使用原型得到Name:"+this.name);
}
var per=new Person("艳杰",21);
per.sayHello(); //输出:使用原型得到Name:艳杰
function Student(){}
Student.prototype=new Person("陶涛",21);
// var stu=new Student();
Student.prototype.grade=5;
Student.prototype.intr=function(){
alert(this.grade);
}
var stu=new Student();
stu.sayHello();//输出:使用原型得到Name:陶涛
stu.intr();//输出:5
这种原型继承的方式存在缺点
缺点:
这种方法缺点比较明显,看起来很不直观,而且子类的方法不能优先于父类方法出现,通过new调用时,不能直接调用父类的构造函数而是要调用子类
2.构造函数实现继承
function Parent(name){
this.name=name;
this.sayParent=function(){
alert("Parent:"+this.name);
}
}
function Child(name,age){
this.tempMethod=Parent;
this.tempMethod(name);
this.age=age;
this.sayChild=function(){
alert("Child:"+this.name+",age:"+this.age);
}
}
var parent=new Parent();
parent.sayParent("州林"); //输出:“Parent:州林
var child=new Child();
child.sayChild("二狗子",24); //输出:“Parent:二狗子”
构造函数的继承方法在通过new调用时,不能直接调用父类的构造函数而是要调用子类。
3.call , apply实现继承
function Person(name,age,love){
this.name=name;
this.age=age;
this.love=love;
this.say=function say(){
alert("姓名:"+name+',年龄:'+age+',love:'+love);
}
}
//call方式
function student(name,age,love){
Person.call(this,name,age,love);
}
//apply方式
function teacher(name,age,love){
Person.apply(this,[name,age,love]);
//Person.apply(this,arguments); //跟上句一样的效果,arguments
}
var per=new Person("回首",25,"涛"); //输出:“武凤楼”
per.say();
var stu=new student("郑志建",18,'我');//输出:“曹玉”
stu.say();
var tea=new teacher("张宝",16,'小黑裙');//输出:“秦杰”
tea.say();
//call与aplly的异同:
//1,第一个参数this都一样,指当前对象
//2,第二个参数不一样:call的是一个个的参数列表;apply的是一个数组(arguments也可以)
将this绑定在Person构造函数上运行,但是会导致没有自己的原型对象,无法共享原型的方法和属性。
4.class继承 extends实现
ES6之后有的方法,比较直观,也符合逻辑
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
class Student { //创建
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
var xiaoming = new Student('小明');
xiaoming.hello();
class PrimaryStudent extends Student {//继承
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
var xiaohong = new PrimaryStudent('小张','三年级')
xiaohong.hello()
xiaohong.myGrade()