脚本宝典收集整理的这篇文章主要介绍了渡一—— 12-1 继承模式,命名空间,对象枚举(上),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
继承1.传统形式 ——> 原型链 过多的继承了没用的属性2.借用构造函数 1.不能继承借用构造函数的原型 2.每次构造函数都要多走一个函数3.共享原型 不能随便改动自己的原型4.圣杯模式
1.传统形式 ——> 原型链
Grand.PRototyPE.lastName = "Ji" function Grand(){ } VAR grand = new Grand(); Father.prototype = grand; function Father(){ this.name = 'hehe' } 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){ Person.call(this,name,age,sex); this.grade = grade; } var student = new Student();
3.共享原型
Father.prototype.lastName = "Deng" function Father(){ } function Son(){ } son.prototype = Father.prototype; var son = new Son(); var father = new Father(); son.lastName //"Deng" Father.lastName //"Deng" //封装继承 function inherIT(Target,Origin){ Target.prototype = Origin.prototype; } inherit(Son,father); Son.prototype.sex = "male" var son = new Son(); var father = new Father(); son.sex //male father.sex //male
4.圣杯模式
//思路 function F(){} F.prototype = Father.prototype; Son.prototype = new F();
Father.prototype.lastName = "Deng" function Father(){ } function Son(){ } function inherit(Target,Origin){ function F(){} F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; //修正constructor Target.prototype.uber = Origin.prototype; //找真正继承自谁 } inherit(Son,father); Son.prototype.sex = "male" var son = new Son(); var father = new Father(); son.lastName //Deng son.sex //male father.sex //undefined // son.__proto__ --> new F().__proto__ --> Father.prototype
//改写 var inherit = (function(){ var F = function(){};//私有化变量 return function (Target,Origin){ F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype; } }()); //闭包,封装实现变量私有化 function Deng(name,wife){ var prepareWife = "xiaozhang";//只有下面的方法能访问,外面Deng.prepareWife访问不了 this.name = name; this.wife = wife; this.divorce = function(){ this.wife = prepareWife; } this.changePrepareWife = function(target){ prepareWife = target; } this.sayPraprewife = function (){ console.LOG(prepareWife) } } var deng = new Deng('deng','xiaoliu');
以上是脚本宝典为你收集整理的渡一—— 12-1 继承模式,命名空间,对象枚举(上)全部内容,希望文章能够帮你解决渡一—— 12-1 继承模式,命名空间,对象枚举(上)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。