1. 程式人生 > >JavaScript繼承的實現

JavaScript繼承的實現

Language popu -a hid set pri 分享 Education pretty

JavaScript繼承有構造函數繼承、原型繼承、復制繼承、構造函數/原型組合繼承等方法,這些繼承方法各有特點。眼下最經常使用的就是構造函數/原型組合繼承。

/**
 * 實現繼承
 * @param  subType    {Function}  子類構造函數
 * @param  superType  {Function}  父類構造函數
 */
function inherit(subType, superType){
    function F(){}
    F.prototype = superType.prototype;

    var p = new F();
    p.constructor = subType;
    subType.prototype = p;
}

/**
 * 父類
 * @param  name  {String}  姓名
 * @param  age   {Number}  年齡
 */
function Person(name, age){ this.name = name; this.age = age; } Person.prototype.getName = function(){ return this.name; }; Person.prototype.setName = function(name){ this.name = name; }; Person.prototype.getAge = function(){ return this.age; }; Person.prototype.setAge = function
(age){
this.age = age; }; /** * 子類 * @param name {String} 姓名 * @param age {Number} 年齡 * @param education {String} 教育程度 */ function Student(name, age, education){ this.education = education; //調用父類構造函數 Person.call(this, name, age); } //實現繼承 //一定要在聲明子類原型方法之前,否則會被覆蓋。

inherit(Student, Person); Student.prototype.setEducation = function(education){ this.education = education; }; Student.prototype.getEducation = function(){ return this.education; }; var person = new Person(‘小明‘, 25); var student = new Student(‘小剛‘, 22, ‘本科‘); person instanceof Person; //true student instanceof Person; //true student instanceof Student; //true

父類屬性及方法

技術分享

子類屬性及方法
技術分享

JavaScript繼承的實現