总结:继承的一些笔记
文章目录
原型链继承
// 父 ==> 构造函数
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayHello = function(){
console.log('说话...')
}
// 子 ==> 构造函数
function Child(name,age){
this.name = name
this.age = age
}
// 改变Child 的原型对象,指向Person的公共属性,达到原型链的继承方式
Child.prototype = new Person()
Child.prototype.constructor = Child
let p = new.Child()
p.sayHello() // '说话...'组合继承
// 父 ==> 构造函数
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayHello = function(){
console.log('说话...')
}
// 子 ==> 构造函数
function Child(name,age){
Person.call(this,name,age) // 继承Person的私有属性
}
// 改变Child 的原型对象,指向Person的公共属性,达到原型链的继承方式
Child.prototype = new Person()
Child.prototype.constructor = Child
let c = new.Child('wc',18)
p.name // 'wc'寄生组合继承
// 父 ==> 构造函数
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayHello = function(){
console.log('说话...')
}
// 子 ==> 构造函数
function Child(name,age){
Person.call(this,name,age) // 继承Person的私有属性
}
// 创建一个空对象,将Person的原型的对象指向空对象,并将空对象的地址赋值给Child的原型对象
Child.prototype = Object.create(Person.prototype)
Child.prototype.constructor = Child
let c = new.Child('wc',18)
p.name // 'wc'Es6 class 继承
class Person{
constructor(name,age){
// 私有属性
this.name = name
this.age = age
}
//sayHello 是共有属性 是原型链上的属性
sayHello(){
console.log('说话...')
}
}
//让 Child类 继承 Person类
class Child extends Person{
constructor(name,age){
super(name,age) // 调用父类的constrctor
}
}
let c = new Child('wc',18)
console.log(c.name) // 'wc'
console.log(c.age) // 18
c.ayHello() // '说话了'
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论