原型模式(Prototype)
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。因为JavaScript的特性, 这一点实现起来格外的简单
代码一:
//父类
class Parent{
constructor(x){
this.x = x;
}
showX(){
alert( this.x );
}
}
//子类1继承
class ChildA extends Parent{
constructor(x,y){
super();
this.y = y;
}
showY(){
alert( this.y );
}
}
//子类2继承
class ChildB extends Parent{
constructor(x,z){
super();
this.z = z;
}
showZ(){
alert( this.z );
}
}
代码二:
let obj = {
sayHello(){
alert( "Hello" );
}
};
let objA = Object.create(obj,{
name :{
writable:true,
configurable :true,
enumerable:true,
value : "AA"
}
});
let objB = Object.create(obj,{
name :{
writable:true,
configurable :true,
enumerable:true,
value : "BB"
}
});
objA.sayHello()
总结:多个类使用到了相同的属性或方法,那我们就可以通过原型继承的方式来创造出类或者实例对象。