JS关于继承的总结
- 方法一 通过原型链
GrandFather.prototype.Lastname = '刘';
function GrandFather() {
}
var grandfather = new GrandFather();
Father.prototype = grandfather;
function Father() {
}
var father = new Father();
Son.prototype = father;
function Son() {
}
var son = new Son();
缺点:会导致继承过多没有用的功能
2. 借用构造函数
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, grade) {
this.grade = grade;
Person.call(this, name, age, sex);
}
var student = new Student();
缺点:1 每次构造函数都要多运行一个函数 2不能借用构造函数的原型
3. 共享原型
Father.prototype.lastname = 'liu';
function Father (){
}
function Son() {
}
Son.prototype = Father.prototype;
var son = new Son ();
var father = new Father();
缺点:不能随意改动原型
4. 圣杯模式
var inherit = (function () {
var F = function () {
}
return function (Target,Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F ();
Target.prototype.constuter = Target;
Target.prototype.uber = Origin.prototype;
}
}());