继承的概念:
在原有的基础之上我们要进行继承,可以直接从父方法或者父类中的属性和方法,达到不用重复定义即可直接使用,就是代码的复用
ES5继承的方式有哪些?
原型链继承:将父方法的实例化对象赋给子方法的原型,子方法既可调用父方法自身的属性和方法,还可以使用父方法原型中的属性和方法,不足地地方就是无法传递参数。
function Nation() {
this.name = '张飞'
this.age = '男'
}
Nation.prototype.skills = '当阳桥喝退百万师'
Nation.prototype.poem = function() {
console.log('子承父之志');
}
function Address() {
this.name = '张星彩'
this.age = '女'
}
Address.prototype = new Nation()
let address = new Address()
console.log(address);
console.log(address.name, address.age, address.skills);
address.poem();
构造函数继承
定义一个父函数和子函数,子函数通过call方法或者allpy改变指向从而实现继承效果,
父方法.call(this,参数列表),缺点是不能使用父方法原型中的属性,可以传递参数
function Car(brand, color) {
this.brand = brand
this.color = color
}
Car.prototype.skills = '直线之王'
function Knsg() {
this.speed = '每小时500公里'
Car.call(this, 'jesko', 'red')
}
let knsg = new Knsg()
console.log(knsg);
Class类及Class继承:
ES6提供了更新传统的语言写法,引入Class类,作为对象的模板,ES6中的class可以当作是一个语法糖,它的大部分功能,ES5都可以做到,新的class写法让对象原型的写法更加清晰
class Jukuzhou {
constructor(name, age, address) {
this.name = name
this.age = age
this.address = address
}
skills() {
console.log('十八般武艺和十八般武器');
}
}
let ydj = new Jukuzhou('妖刀姬', '女', '森罗谷')
console.log(ydj);
let jch = new Jukuzhou('季沧海', '男', '不舟滩')
console.log(jch);
let gqh = new Jukuzhou('顾清寒', '女', '天人城')
console.log(gqh);
class的继承:
还可以使用extends关键字实现,super()父类的方法
class Animal {
constructor(name) {
this.name = name // 指定名字
}
main() {
console.log(`${this.name}练习两年半`);
}
}
class Chicken extends Animal {
static num = 1;
constructor(name) {
super(name)
this.overalls = '背带裤'
this.love = '唱跳rap篮球'
}
skills() {
console.log(`${this.name}会唱跳rap篮球`);
}
}
let chicken = new Chicken('鸡哥')
console.log(chicken);
chicken.main()
chicken.skills()
版权声明:本文为Hwlyhl原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。