🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
<mark>1. Person.call函数继承</mark>:继承Person所有的成员,但不包括原型的成员 ```js function Person(name, age) { this.type = "human"; this.name = name; this.age = age; this.getName = function() { console.log(this.name) } } function Student(name, age) { // 继承Person所有的成员,但不包括原型的成员 Person.call(this, name, age); // this就是Student对象 } var s1 = new Student("Jack", 21); console.log(s1.type, s1.name, s1.age); // human Jack 21 s1.getName(); // 21 ``` <mark> 2. 拷贝继承(for-in)</mark>:继续所有成员,包括原型对象成员 ```js function Person(name, age) { this.type = "human"; this.name = name; this.age = age; } Person.prototype.getName = function() { console.log(this.name); } function Student(name, age) { // 继承Person所有的成员,但不包括原型的成员 Person.call(this, name, age); } for(var key in Person.prototype) { // 通过拷贝来继承原型的成员 Student.prototype[key] = Person.prototype[key]; } var s1 = new Student("Jack", 21); s1.getName(); // Jack ``` <mark>3. 原型继承</mark>:继续所有成员,包括原型对象成员 ```js function Person (name, age) { this.type = 'human' this.name = name this.age = age } Person.prototype.sayName = function () { console.log('hello ' + this.name) } function Student (name, age) { // 继承Person的所有成员,但不包括原型中的成员 Person.call(this, name, age) } // 利用原型的特性实现继承原型的所有成员 Student.prototype = new Person() var s1 = new Student('张三', 18) console.log(s1.type) // => human s1.sayName() // => hello 张三 ```