个人感觉作为一个程序员在编写程序时,快捷,高效,简便,是写代码的最大特点。在相对于相同的代码不用去写第二遍,在别处写好的功能在这里直接拿来去用,就是快捷的一种方式。
继承模式
在继承模式的发展史上,出现过很多种继承模式,经过不断完善最终成就完美模式
原型链
别人的东西我如果需要我自己拿来用。
Grand.prototype.lastName = "wang";
function Grand(){]
var grand = new Grand();
Father.prototype = grand;
function Father(){}
var father = new Father();
Son.prototype = father;
function Son(){}
var son = new Son();
借用构造函数
借用构造函数运动到call/apply的知识点,不懂得 点击这里function Person(name,age){
this.name = name;
this.age = age;
}
function Student(name,age,no){
Person.call(this,name,age);
this.no = no;
}
var student = new Student('wang',20,'123456789');
这种方法有不足的地方,相对于执行student对象,两个构造函数的方法都要调用,会造成浏览器运行量大,还有不能使用借用的构造函数的原型。当然在程序需要的时候,是可以这样构造对象的。
共享原型
这个共享原型就真正相当于继承了。
Person.prototype.lastName = "wang";
function Person(){}
function Studnet(){}
Student.prototype = Person.prototype;
var person = new Person();
var student = new Student();
这样的形式还可以封装在函数里面。
function inherit(Target,Origin){
Target.prototype = Origin.prototype;
}
inherit(Student,Origin);
这种方法还不是最完美的写法,也有不好的地方,继承之后,如果你想在Student中加个属性的话,在Person中也加了,这就导致进行不必要的添加。接下来就有完美模式的产生
圣杯模式
圣杯模式是继承的完美模式,在共享原型的基础上,完善了共享原型的不足。
Person.prototype.lastName = "wang";
function Person(){}
function Studnet(){]
function inherit(Target,Origin){
function F(){}
F.prototype = Origin.prototype;
Target.prototype =new F();
}
inherit(Student,Person);
var student = new Student();
var person = new Person();
这样的话,在子代运用constructor属性找自身构造函数的时候,找到的事父代的构造函数。还可以在子代原型中加uber属性找到子代是继承来自的哪个父代。
function inherit(Target,Origin){
function F(){}
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
inherit(Student,Person);
在上述完美继承函数中运用了中间函数,这样也是可以调用F中间函数的,运用闭包---私有变量和立即执行函数的知识再进行修改。
var inherit = (function(){
var F = function(){};
return function(Targin,Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}())
上述继承模式最完美模式,立即执行函数和返回函数形成闭包,构成F函数为私有函数(变量)。
JavaScript语言我个人感觉是最有意思的了,我也是一个初学者,遇到问题,喜欢在博客上分享,
也希望能帮到大家。
一个初学者,有什么不足或者纰漏的话,希望在下面评论出来,相互学习,共同进步。
--主页传送门--