渡一—— 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');
标签:function,渡一,12,Father,Son,枚举,var,new,prototype 来源: https://www.cnblogs.com/lisa2544/p/15308184.html