首页 > Web开发 > 详细

js中的继承

时间:2021-07-21 17:14:02      阅读:41      评论:0      收藏:0      [点我收藏+]

继承的发展史

1.传统形式(原型继承) ,过多继承了没有用的属性

例子:

Grand.prototype.lastName = ‘张三‘;
function Grand(){this.age = 25}
var grand = new Grand();
Father.prototype = grand;
function Father(){this.sex = ‘男‘}
var father = new Father();
Son.prototype = father;
function Son(){}
var son = new Son();
console.log(son.lastName);

2.借用构造函数(call/apply),不能继承构造函数的原型,多走一个函数

例子:

// 借用构造函数
A.prototype.lastName = ‘李四‘;
function A(){
    this.age = 26;
    this.name = ‘张三‘;
    this.sex = ‘男‘;
}
function B(age,name,sex,address){
    A.call(this,age,name,sex);
    this.address = ‘beijing‘;
}
var b = new B();
console.log(b.lastName);

3.共享原型,不能随便改动自己的原型 (使用广)

// 共享原型
A.prototype.lastName=‘王五‘;
function A(){}
B.prototype = A.prototype;
function B(){}
var b = new B();
console.log(b.lastName);

// 封装一下
function extend(Target,Origin){
    Target.prototype = Origin.prototype;
}
A.prototype.lastName = ‘赵六‘;
function A(){}
function B(){}
var b  = new B();
extend(B,A);
console.log(b.lastName);

4.圣杯模式

// 圣杯模式(完美版继承)
var extend = (function(){
    var F = function(){};
    return function(Target,Origin){
        F.prototype = Origin.prototype;
        Target.prototype = new F();
        // 让构造函数回归
        Target.prototype.constructor = Target;
        // Target到底继承谁
        // Traget.prototype.uber = Origin.prototype;
    }
}())
A.prototype.lastName = ‘田七‘;
function A(){}
function B(){}
extend(B,A);
var b = new B();
console.log(b.lastName);

js中的继承

原文:https://www.cnblogs.com/chenhuaiyou/p/14847230.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!