class human {
constructor(height, weight){
this.height = height;
this.weight = weight;
}
c(){
return this
}
}
const a = new human(178, 67);
cc = a.c;
console.log(cc()) // undefined
cc = a.c();
console.log(cc) // human { height: 178, weight: 67 }
繼承父 class
如果class內 function名稱相同會繼承,但也可以直接在子類別覆蓋
function Animal (name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise.');
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}
var d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
class 換成 function
class Animal {
constructor(name){
this.name = name
}
}
// 等同於
function Animal (name) {
this.name = name;
}
不同class 傳遞參數
假設其上層的 js
const infoBox = new InfoBox(data);
const worldMap = new Map(data, updateYear);
// 這時當 worldMap 內執行了 this.updateYear 時會執行父層的 updateYear,
// 這時可存取 infoBox 並將直傳入
const updateYear = (year) => {
// year 假設來自 worldMap
// infoBox 內有個 updateTextDescription function
infoBox.updateTextDescription({ activeYear: year });
};
呼叫父類別方法
class a {
constructor(cc, bb) {
console.log(cc, bb)
}
test() {
console.log('test')
}
}
繼承
class b extends a {
constructor(cc, bb) {
super(33, 44) // 傳入 a 的 constructor
console.log(222)
super.test()
}
}
c = new b
// 3 33 44
// 4 222
// 6 test
或是
b.prototype.cc()
// test
c.__proto__.test()
// test