js继承模式

本文深入探讨JavaScript中的多种继承模式,包括原型链、借用构造函数、共享原型、圣杯模式及私有变量应用,对比每种模式的特点与局限,为开发者提供全面的JS继承实践指南。

js继承模式

传统形式 ----> 原型链 过多的继承了没用的属性

Grand.prototype.lastName = "1";
function Grand(){
}
var grand = new Grand();
Father.prototype = grand;
function Father() {
}
var father = new Father();
Son.prototype = father;
function Son() {
}
var son = new Son();

借用构造函数

 不能继承借用构造函数的原型
 每次构造函数都要夺多走一个函数
function Person(name, sex, age) {
     this.name = name;
     this.sex = sex;
     this.age = age;
 }

 function Student(name, sex, age, grand) {
     Person.call(this, name, sex, age);
     this.grand = grand;
 }

 var student = new Student();

共享原型 //缺点 :一个值改另一个也跟这改

 不能随便改动自己的原型
复制代码
Father.prototype.lastName = 'Deng';

 function Father() {

 }

 function Son() {

 }
 function inherit(Target , Origin){
     Target.prototype = Origin.prototype
 }
 inherit(Son , Father);
var son = new Son();
var father = new Father();

圣杯模式

 function inherit(Target , Origin){
     function F(){}
     F.prototype = Origin.prototype;
     Target.prototype = new F();
     Target.prototype.constructor = Target;
     Target.prototype.uber = Origin.prototype;
 }
 Father.prototype.lastName = 'Deng';
 function Father() {
 }

 function Son() {
 }

 inherit(Son , Father);
 var son = new Son();
 var father = new Father();

私有化变量的应用

 function Li(name , wife){
     var preareWife = "xiaozhang";
     this.name = name;
     this.wife = wife;
     this.divorce = function () {
         this.wife = preareWife;
     };
     this.changPrepareWife = function (target) {
         preareWife = target;
     };
     this.sayPrapreWife = function () {
         console.log(preareWife);
     }
 }
 var li = new Li("li" , "xiaoLi")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李学软件

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值