js中如何实现类
方法1:使用原型
function Person(name){
this.name = name
this.nose = 1
this.eye = 2
}
Person.prototype.say = function () {
console.log('你好')
}
Person.Prototype.eat = function(){
console.log('吃饭')
}
const p1 = new Person('ls')
p1.say()
方法2: 使用class类
class Person {
constructor (name) {
this.name = name
this.nose = 1
this.eye = 2
}
say(){
console.log('你好')
}
eat(){
console.log('吃饭')
}
}
const p2 = new Person('zs')
p2.say()
如何实现继承
方法1:使用原型链
function Animal(legsNumber){
this.legsNumber = legsNumber
}
Animal.prototype.kind = '动物'
function Dog(name){
this.name = name
Animal.call(this, 4) // 关键代码1
}
Dog.prototype.__proto__ = Animal.prototype // 关键代码2,但这句代码被禁用了,怎么办
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
const d1 = new Dog('啸天') // Dog 函数就是一个类
console.dir(d1)
方法2: 使用class
class Animal{
constructor(legsNumber){
this.legsNumber = legsNumber
}
run(){}
}
class Dog extends Animal{
constructor(name) {
super(4)
this.name = name
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
}