js构造函数
function MathHandle(x,y){
this.x=x;
this.y=y;
}
MathHandle.prototype.add=function(){
return this.x+this.y;
}
var m=new MathHandle(1,2);
console.log(m.add())
继承
function Animal(){
this.eat=function(){
console.log('Animal eat')
}
}
function Dog(){
this.bark=function(){
console.log('Dog bark')
}
}
//Dog绑定原型继承Animal,得到Animal的实例
Dog.prototype=new Animal();
var gou=new Dog();
gou.eat();//Animal eat
gou.bark();//Dog bark
class基本语法
继承
class MathHandle{
constructor(x,y){
this.x=x;
this.y=y
}
add(){
return this.x+this.y;
}
}
const m=new MathHandle(1,2);
m.add()
class Animal{
constructor(name){
this.name=name
}
eat(){
console.log('Animal eat')
}
}
class Dog extends Animal{
constructor(name){
super(name)//指向更高级被继承的Animal的constructor,将name传过去
this.name=name
}
bark(){
console.log('Dog bark')
}
}
const dog=new Dog();
dog.eat();
dog.bark();
总结:
1. class在语法上属于面向对象的写法
2.class实现继承简洁易于理解
3.采用的偏向后台语言的类的写法
4.本质还是语法糖,使用prototype
网友评论