继承,多态

javascript是一门面向对象的编程语言–继承,多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function Animal () {}
function Dog () {}

Object.defineProperties(Animal.prototype, {
name: {
value() {
return 'Animals'
}
},
say() {
return `i'm ${this.name()}`
}
})

Dog.prototype = Object.create(Animal.prototype, {
constructor: {
value: Dog,
enumerable: false
},
name: {
value() {
return 'Dog'
}
}
})
// dog instanceof Animal == true
// dog.__proto__.__proto__ == Animal.prototype
// dog.__proto__ === Dog.prototype
// DOMStringMap.prototype.__proto__ == Animal.prototype
Dog.prototype = Object.create(Animal)
console.log(new Dog() instanceof Animal)
console.log(Dog.prototype.constructor)

// es6

class Animal {
name () {
return 'Animal'
}
say () {
return `i'am ${this.name()}`
}
}
class Dog extends Animal {
name() {
return 'Dog'
}
}
console.log(new Dog() instanceof Animal)