父类学习
function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { eat: function () { console.log(this.name + '正在吃饭...'); }, sang: function () { console.log(this.name + '正在唱歌...'); } }; var liuyu = new Person('刘雨', 26);
子类this
function Student(name, age, score) { Person.call(this, name, age); this.score = score; }
封装一个 extends 方法prototype
//子类 extends 父类 Function.prototype.extends = function (func, options) { for (var key in func.prototype) { this.prototype[key] = func.prototype[key]; } for (var name in options) { this.prototype[name] = options[name]; } };
子类能够继承父类的属性和方法,也能够扩展本身的属性和方法。extends 方法参数:1.父类 2.须要扩展的属性和对象的一个对象集合。code
Student.extends(Person, { study: function () { console.log(this.name + '正在学习...'); } }); var can = new Student('can', 22, '良好'); can.eat(); can.work();