JS构造函数
//JS构造函数
function MathHandle(x,y){
this.x = x;
this.y = y;
}
MathHandle.prototype.add = function(){
return this.x + this.y;
}
let test = new MathHandle(1,2);
console.log(test.add());
console.log(typeof MathHandle);
console.log(MathHandle.prototype.constructor === MathHandle);
console.log(test.__proto__ === MathHandle.prototype);
// 3
// function
// true
// true
Class基本语法
//Class语法
class MathHandle {
//构造器
constructor(x, y) {
this.x = x;
this.y = y;
}
add() {
return this.x + this.y;
}
}
let test2 = new MathHandle(3, 7);
console.log(test2.add());
console.log(typeof MathHandle);
console.log(MathHandle.prototype.constructor === MathHandle);
console.log(test2.__proto__ === MathHandle.prototype);
class本身只是语法糖,
继承
// //动物
// function Animal(){
// this.eat = function(){
// console.log('Animal eat');
// }
// }
// //狗
// function Dog(){
// this.bark = function(){
// console.log('Dog bark');
// }
// }
// //绑定原型,实现继承
// Dog.prototype = new Animal();
// let erha = new Dog();
// erha.bark();
// erha.eat();
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(this.name + ' eat');
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
bark() {
console.log(this.name + ' bark');
}
}
let dog = new Dog('erha');
dog.bark();
dog.eat();
总结:
Class在语法上更加贴合面向对象的写法,Class实现继承更加易读,更易于后端开发人员的学习,但是本质上还是语法糖,使用的还是prototype原型的继承方式。