//經過構造函數建立實例對象 function ClassA(x, y){ this.x = x; this.y = y } ClassA.prototype.add = function(){ return this.x + this.y } var m = new ClassA(1, 2); console.log(m.add()) /* 基本上,ES6 的class能夠看做只是一個語法糖,它的絕大部分功,ES5 均可以作到,新的class寫法只是讓對象原型的寫法更加清晰、更像面向對象編程的語法而已。 */ // es6 class關鍵字寫法 class ClassB { constructor(x, y){ this.x = x; this.y = y } add(){ return this.x + this.y } } const m1 = new ClassB(1, 2) console.log(m1.add()) typeof ClassB //"function" ClassB.prototype.constructor === ClassB // true m1.__proto__ === ClassB.prototype // true
js繼承,經過將原型賦值爲父類的實例對象實現繼承es6
function Animal(){ this.eat = function(){ console.log('Animal eat') } } function Dog(){ this.bark = function(){ console.log('Dog bark') } } Dog.prototype = new Animal() var hsq = new Dog() hsq.eat() hsq.bark() //es6 class語法繼承 class Animal { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } class Dog extends Animal { constructor(name) { super(name) this.name = name } say() { console.log(`${this.name} say`) } } const dog = new Dog('哈士奇') dog.say() dog.eat()