只继承公有的
//es5
Children.prototype = Object.create(Parent.prototype)
//es6
Object.setPrototype(Children.prototype,Parent.prototype)
es5类的继承
//ES5的继承
/*父类*/
function Person(name) {
this.name = name;
}
Person.prototype.showName = function () {
console.log('我的名字是'+this.name);
};
/*子类*/
function Student(name,skill) {
Person.call(this,name);//继承属性,这里要改变this指向,如果有参数,要传参进去
this.skill = skill;
}
/*继承*/
/* function extend(Obj1,Obj2) {
for ( item in Obj1){
Obj2[item] = Obj1[item];
return Obj2;
}
}
extend(Person.prototype,Student.prototype);//原型继承方法
*/
Student.prototype = new Person(); //直接继承方法
Student.prototype.showSkill = function () {
console.log("我的技能是:"+this.skill);
};
/*面向对象实例化*/
var student = new Student("marin","跑路");
console.log(student.name);
student.showName();
student.showSkill();
es6类的继承
//ES6的继承
/*父类*/
class Person{
constructor(name){
this.name = name;
}
showName(){
console.log(`我的名字是:${this.name}`)
}
}
/*子类继承 extends 既能一下继承父类方法也可以一下继承父类属性 */
class Student extends Person{
constructor(name,skill){
super(name);//用于拉取父类的构造函数里的属性 有参数就要传参数 也可用 args 实参集合
this.skill = skill;
}
//子类重写showName 这样是不会改变父级的方法的,但是这样父级原来的想要在子类里面使用的就没有了
/* showName(){
console.log("我是子类重写的方法")
}*/
//另外一种子类重写放啊发,可以保证从父级继承来的方法能够执行的同时,还可以保证子类自己做自己的事;
showName(){
super.showName();//保证从父类继承来的方法执行
console.log(`我是子类基于父类方法下,子类想要执行的额外操作`);//子类想要执行的操作
}
showSkill(){
console.log(`我的技能是:${this.skill}`)
}
}
/*面向对象实例化*/
// let person = new Person("marin");
let student = new Student("faker","饮水机");
//person.showName();
//console.log(student.name);
student.showName();
student.showSkill();