ES5 实现继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a noise.');
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(this.name + ' barks.');
};

var dog = new Dog('Rex', 'Labrador');
dog.speak(); // 输出: Rex makes a noise.
dog.bark(); // 输出: Rex barks.

ES6 实现继承(不同 class 和 extends)

1
2
3
4
function Foo() { }
function Bar() { }

Object.setPrototypeOf(Bar.prototype, Foo.prototype);
更新于 阅读次数