class语法js构造函数

44次阅读

共计 910 个字符,预计需要花费 3 分钟才能阅读完成。

// 通过构造函数创建实例对象
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()

正文完
 0