標籤:.net setname ati tty person prototype pre 使用 rac
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; //truestudent instanceof Person; //truestudent instanceof Student; //true
父類屬性及方法
子類屬性及方法
JavaScript繼承的實現