实现继承的方法

圣杯模式

//简易版
function extend(Target,Origin){
    function F(){}
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constructor = Target;
    Target.prototype.uber = Origin;  
}

//YUI库中的写法

var extend = (function(){
    function F(){}
    return function(Target,Origin){
        F.prototype = Origin.prototype;
        target.prototype = new F();
        target.prototype.constructor = Target;
        target.prototype.uber = Origin
    }
})()

借用原型链实现继承

基本思想:利用原型让一个引用类型继承另一个引用类型的属性和方法,实现的本质是重写原型对象,代之以一个新类型的实例。

function SuperType(){
    this.property = true
}
SuperType.prototype.getSuperValue = function(){
    return this.property;
}
function SubType(){
    this.subProperty = false;
}
//继承SuperType
SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function(){
    return this.subProperty;
}
var instance = new SubType();

instance.getSuperValue()//true
instance.getSubValue()//false

缺点

  1. 包含引用类型值的原型属性会被所有实例共享。这样,一个实例修改了原型对象中引用类型值的原型属性,会在另外一个实例对象上也体现出来这种修改。
function SuperType(){
    this.color =['red','green','blue']
}
function SubType(){}

SubType.prototype = new SuperType();
var instance1 = new SubType();
instance1.color.push('yellow');

var instance2 = new SubType();
instance2.color;//['red','green','blue','yellow']
  1. 在创建子类的实例时,无法向超类的构造函数中传递参数。

借用构造函数

思想:在子类构造函数的内部调用超类构造函数

function SuperType(name,age){
    this.name = name;
    this.age = age;
}

function SubType(name,age,gender){
    SuperType.call(this,name,age);//就是这一步继承了superType。
    this.gender = gender;
}

组合继承

function SuperType (name){
    this.name = name;
}

SuperType.prototype.sayName =function(){
    console.log(this.name);
}

function SubType (name,age){
    SuperType.call(this,name);
    this.age = age;
}

SubType.prototype = Object.create(SuperType.prototype);;
SubType.prototype.constructor = SubType;


  转载请注明: TomoFur 实现继承的方法

 上一篇
网络攻击 网络攻击
Cross-Site-Scripting(xss)跨站脚本攻击为了不和层叠样式表的缩写混淆,故将跨站脚本攻击写为XSS.恶意攻击者往Web页面里插入恶意Script代码,当用户浏览该页面时,嵌入Web里面的Script代码会被执行,从而达到
2019-08-07
下一篇 
类型转换 类型转换
这个知识点还是有一些繁琐。需要认真理解并记忆 ToStringToString负责处理非字符串到字符串的强制类型转换 基本类型的值转换为字符串 null 转化为'null' undefined 转化为'undefined' true
2019-08-06
  目录