//通过构造函数创建实例对象
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继承,通过将原型赋值为父类的实例对象实现继承
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()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。