继承与原型
第一种 原型链
基本思想:利用原型让一个引用类型继承另外一个引用类型的属性和方法。
function Super(){
this.name = "silva";
};
Super.prototype.getValue = function(){
return this.name ;
};
function Sub(){
this.name = "程";
};
Sub.prototype = new Super();
Sub.prototype.getValue = function(){
return this.name;
};
var xxx = new Sub();
alert(xxx.getValue());
第二种 借用构造函数
基本思想:在子类型构造函数的内部调用超类构造函数,通过使用call()和apply()方法可以在新创建的对象上执行构造函数。
function Super(){ this.colors = ["red","green","blue"]; } function Sub(){ Super.call(this);//继承Super } var instance = new Sub(); alert(instance.colors)
第三种 组合继承
基本思想:将原型链和借用构造函数的技术组合在一块,从而发挥两者之长的一种继承模式。
function Super(){ this.name = "Silva"; this.colors = ["red","green","blue"]; } Super.prototype.sayName = function(){ alert(this.name) } function Sub(name,age){ Super.call(this,name);//继承属性 this.age = age; } //继承方法 Sub.prototype = new Super();//继承原型 Sub.prototype.constructor = Super;//构造函数 Sub.prototype.sayAge = function(){ console.log(this.age); }
浙公网安备 33010602011771号