码迷,mamicode.com
首页 > Web开发 > 详细

js中的继承

时间:2017-04-03 23:47:39      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:可见   prot   push   函数   原型链   this   组合   继承   instance   

实现原型链有一种基本模式,其代码大致如下:
 
function A(){
     this.property = true;
}
A.prototype.getAvalue = function(){
  return this.property;   
};
function B(){
     this.property = false;
}
//继承了A
B.prototype = new A();
B.prototype.getBvalue = function(){
     return this.property;
};
var instance = new B();
console.log(instance.getBvalue());//true;
 
 借用构造函数
 
function A(){
     this.color = ["red","blue"];
}
 
function B(){
     // 继承了A
     A.call(this);
var instance1 = new B();
instance1.color.push("yellow");
console.log(instance1.color);//red,blue,yellow;
 
var instance2 = new B();
console.log(instance2.color);//red,blue;
 
1,传递参数
相对于原型链而言,借用构造函数有一个很大的优势,既可以在子类型构造函数中向超类型构造函数传递参数;如下:
 
function A(){
     this.name = name;
}
 
function B(){
     //继承了A,同时传递参数
     A.call(this,"hello");
     // 实例属性;
     this.age = 27;
}
var instance = new B();
console.log(instance.name);//hello
console.log(instance.age);//27
2.借用构造函数的问题:如果仅仅是借用构造函数那么也将无法避免构造函数模式存在的问题,方法都在构造函数中定义,因此函数的复用就无从谈起。而且在超类型的原型中定义的方法相对,对子类型而言是不可见的,造成的结果是所有的类型都只能使用构造函数模式。
三.组合继承
组合继承,有时也叫为经典继承,指将原型链和借用构造函数的技术组合到一块,从而发挥二者之长的一种继承模式,思路是:使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。
 
function A(name){
     this.name = name;
     this.colors = ["red","blue"];
}
A.prototype.sayName = function(){
     alert(this.name);
};
function B(name,age){
     A.call(this,name);
     this.age = age;
}
// 继承方法
B.prototype = new A();
B.prototype.constructor = B;
B.prototype.sayAge = function(){
     alert(this.age);
};
var instance1 = new B("hehe",27);
instance1.colors.push("yellow");
instance1.sayName();//hehe
instance1.sayAge();//27;
 
var instance2 = new B("haha",28);
console.log(instance2.colors);//red,blue
instance1.sayName();//haha
instance1.sayAge();//28;

js中的继承

标签:可见   prot   push   函数   原型链   this   组合   继承   instance   

原文地址:http://www.cnblogs.com/wtfu/p/6663949.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!