class Animal {
constructor(name = "Animal",lag = 4) {
this.name = name;
this.lag = lag;
}
run(lag) {
if(lag) {
this.lag = lag
}
console.log(`${this.name}用${this.lag}只脚跑步!`)
}
stop() {
console.log(`${this.name}静止不动!`)
}
}
let animal = new Animal("first animal")
接下来如果想要创建另外一个cat class,可以基於class animal做延伸,因为animal里面的method都是可以套用在cat身上的:
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
}
let cat = new Cat("White cat")
cat.run(4); // White cat用4只脚跑步!
假设在class Cat中有跟class Animal相同的函数,那cat会优先取用Cat.prototype中的方法:
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
console.log(`${this.name}静止跑步!`)
}
}
let cat = new Cat("White cat")
cat.stop(); // White cat静止跑步!
如果要取用Animal的stop函数可以使用super(...):
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
super.stop();
}
}
let cat = new Cat("White cat")
cat.stop(); // White cat静止不动!
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
setTimeout(() => super.stop(),1000)
}
}
let cat = new Cat("White cat")
cat.stop(); // White cat静止不动!
如果是以function的形式则会报错:
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
setTimeout(function() {super.stop()},1000)
}
}
let cat = new Cat("White cat")
cat.stop(); // 'super' keyword unexpected here
上面例子中class Cat的constructor都是继承class Animal的:
console.log(Cat.constructor===Animal.constructor)
如果直接新增constructor,以下写法会报错:
class Animal {
constructor(name = "Animal",lag = 4) {
this.name = name;
this.lag = lag;
}
run(lag) {
if(lag) {
this.lag = lag
}
console.log(`${this.name}用${this.lag}只脚跑步!`)
}
stop() {
console.log(`${this.name}静止不动!`)
}
}
class Cat extends Animal {
constructor(name = "Animal",lag = 4,color = white) {
this.name = name;
this.lag = lag;
this.color = color;
}
jump() {
console.log(`${this.name} hide!`)
}
}
let cat = new Cat(); // Must call super constructor in derived class before accessing 'this' or returning from derived constructor
extend的class如果要新增自己的constructor必须调用super,而且要在使用this之前:
class Animal {
constructor(name = "Animal",lag = 4) {
this.name = name;
this.lag = lag;
}
run(lag) {
if(lag) {
this.lag = lag
}
console.log(`${this.name}用${this.lag}只脚跑步!`)
}
stop() {
console.log(`${this.name}静止不动!`)
}
}
class Cat extends Animal {
constructor(name,lag,color = 'white') {
super(name,lag);
this.color = color;
}
jump() {
console.log(`${this.name} hide!`)
}
}
let cat = new Cat();
console.log(cat.color); // white
##让我们来学习演算法吧,此为阅读[https://pjchender.blogspot.com/2...
Colab连结 接着昨天讨论到的 Cross Entropy ,今天把重点放到了 BinaryCro...
『像素操作(Pixel Manipulation)』 顾名思义就是要去以单一像素为最小单位来进行操作...
昨天我们解决了登入时的小错误 欢迎各位进入到主画面 简单的跟各位介绍一下基本功能 我们可以点选上方的...
我在学生时代的大魔王-回圈loop 曾经写了一个无限回圈,让电脑执行时当机XD loop以英文直接来...