基于原型
function Parent(name1){
this.name1 = name1
}
Parent.prototype.pMethod = function(){
console.log(this.name1)
}
function Child(name2, name1){
Parent.call(this, name1)
this.name2 = name2
}
Child.prototype.__proto__ = Parent.prototype
//上面这句代码的古板写法应该是下面三句
//const empty = function(){}
//empty.prototype = Parent.prototype
//Child.prototype = new empty()
Child.prototype.cMethod = function(){
console.log(this.name2)
}
//如果写成下面这种,就扣两分
//Child.prototype = {
// cMethod: function(){
// console.log(this.name2)
// }
//}
基于 class
class Parent{
constructor(name1){
this.name1 = name1
}
pMethod(){
console.log(this.name1)
}
}
class Child extends Parent{
constructor(name2, name1){
super(name1) // 得分点
this.name2 = name2
}
cMethod(){
console.log(this.name2)
}
}
参考自饥人谷课程内容