实现类
使用原型
function Point(x, y) {
this.x = x
this.y = y
}
Point.prototype.toAdd = function () {
return this.x + this.y
}
Point.prototype.toSub = function () {
return this.x - this.y
}
let p = new Point(1, 11)
console.log(p.toAdd(), 'toAdd')
console.log(p.toSub(), 'toSub')
使用class
class Point1 {
constructor(x, y) {
this.x = x
this.y = y
}
toAdd = function () {
return this.x + this.y
}
toSub = function () {
return this.x - this.y
}
}
let p1 = new Point1(1, 11)
console.log(p1.toAdd(), 'toAdd1')
console.log(p1.toSub(), 'toSub1')
实现继承
使用原型
function Animal(legNumber) {
this.legNumber = legNumber
}
Animal.prototype.kind = "动物"
Animal.prototype.run = function () {
console.log(`我可以跑 我有${this.legNumber}条腿`)
}
function Dog(name) {
this.name = name
Animal.call(this, 4)
}
let f = function () {
}
f.prototype = Animal.prototype
Dog.prototype = new f()
Dog.prototype.kind = '狗'
Dog.prototype.say = function () {
console.log(`汪汪汪~ 我是${this.name},我有${this.legNumber}条腿。`)
}
let wangzai = new Dog('旺仔')
wangzai.say()
wangzai.run()
console.log(wangzai.kind)
使用class
class Animal1 {
constructor(legNumber) {
this.legNumber = legNumber
}
run = function () {
console.log(`我可以跑 我有${this.legNumber}条腿`)
}
}
class Cat extends Animal1 {
constructor(name) {
super(4);
this.name = name
}
say = function () {
console.log(`喵喵喵~ 我是${this.name},我有${this.legNumber}条腿。`)
}
}
let kaiti = new Cat('凯蒂')
kaiti.say()
kaiti.run()