原型链继承
function Person (age) {
this.age = age || 18
}
Person.prototype.sleep = function () {
console.log('sleeping')
}
function Programmer() {}
Programmer.prototype = new Person ()
Programmer.prototype.code = function () {
console.log('coding')
}
let jon = new Programmer()
jon.code()
jon.sleep()
jon instanceof Person
jon instanceof Programmer
Object.getPrototypeOf(jon)
jon.__proto__
借用构造函数继承
function Animal(speices){
this.speices = speices;
this.write = function(){
console.log(speices + "呜哈哈");
}
}
Animal.prototype.say = function(){
console.log("我好饿!");
}
function Dog(speices){
Animal.call(this,speices);
}
var dog1 = new Dog("中华田园犬");
var dog2 = new Dog("德国牧羊犬");
dog1.write();
dog2.write();
dog1.say();
dog2.say();
组合继承
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function() {
console.log('hello world');
}
function Student(gender, name, age) {
this.gender = gender;
Person.call(this, name, age);
}
Student.prototype = new Person();
Student.prototype.study = function() {
console.log('study');
}
const s = new Student('男', 'Jack', 18);
console.log(s);
利用拷贝继承
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function() {
console.log('hello world');
}
function Student(gender, name, age) {
this.gender = gender;
const p = new Person(name, age);
for( let key in p) {
Student.prototype[key] = p[key];
}
}
Student.prototype.study = function() {
console.log('study');
}
const s = new Student('男', 'Jack', 18);
console.log(s);
寄生继承
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function() {
console.log('hello world');
}
function Student(gender) {
this.gender = gender;
}
Student.prototype = Person.prototype;
Student.prototype.study = function() {
console.log('study');
}
const s = new Student('男');
console.log(s);
寄生式组合继承
function Person(name, pets) {
this.name = name;
this.pets = pets;
}
Person.prototype.run = function () {
console.log('跑');
};
function Student(num, name, pets) {
Person.call(this, name, pets);
this.num = num;
}
function Temp() {}
Temp.prototype = Person.prototype;
var stuPrototype = new Temp();
Student.prototype = stuPrototype;
stuPrototype.constructor = Student;
var stu = new Student('001', '张三', ['小花']);
console.log(stu);
ES6类继承
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function() {
console.log('hello world');
}
class Student extends Person {
constructor(gender, name, age) {
super(name, age);
this.gender = gender;
}
study() {
console.log('study');
}
}
const s = new Student('男', 'Jack', 18);
console.log(s);