继承发展史
1.传统形式-->原型链
过多的继承了没用的属性
2.借用构造函数
不能继承借用构造函数的原型
每次构造函数都要多走一个函数
3.共享原型
不能随便改动自己的原型
4.圣杯模式
1.eg:
Grand.prototype.lastName = "Deng"
function Grand() {
}
var grand = new Grand();
Fater.prototype = grand;
function Fater() {
this.name = 'xuming';
}
var father = new Fater();
Son.prototype = father;
function Son() {
this.hobbit = 'smoke';
}
var son = new Son();
2.eg:
function Person(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name,age,sex,tel,grade) {
Person.call(this,name,age,sex);
this.tel = tel;
this.grade = grade;
}
var student = new Student('sunny',123,'male',139,2020);
3.eg:
Father.prototype.lastName = "Deng";
function Father() {
}
function Son() {
}
//第一种方法:
//Son.prototype = Father.prototype
//var son = new Son();
//var father = new Father();
//第二种方法:
function inherit(Target,Origin) {
Target.prototype = Origin.prototype;
}
inherit(Son,Father);
var son = new Son(); //必须先继承后用
4.圣杯模式eg:
function inherit(Target,Origin) {
function F() {}; //利用一个空的函数作为中间层,进行转换
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = 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 inherit(Target,Origin) {
function F() {}; //利用一个空的函数作为中间层,进行转换
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = Target;
Target.prototype.uber = Origin.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 preparWife = "xiaozhang";
this.name = name;
this.wife = wife;
this.divorce = function() {
this.wife = preparWife;
}
this.changePrepareWife = function(target) {
preparWife = target;
}
this.sayPraprewife = function() {
console.log(preparWife);
}
}
var deng = new Deng('deng','xiaoliu');