javaScript面向对象编程二

JS的继承、多态


构造函数的继承

JS中的继承是一种对象冒充来实现继承功能,而不是其他语言中定义的继承

funciton A(color){
	this.color=color;
	this.saycolor=function()
	{
		alert(this.color);
	}
} function B (color){
	this.AB=A;
	this.AB(color);
	delete this.AB;
}		
	

注释:B函数中 使用this.AB=A 其实就是用AB这个属性等于A函数,也就是AB具有了A函数的属性及其方法。通过this.AB(color),也就是调用了A函数的方法,此时A中的this指向AB,this.AB的this指向B,也就使B具有了相应的属性和方法。使用过后要删除AB,其实就是删除A和B之间的连接,因为这里的继承和其他语言中的继承不同,他其实就是一种调用。如果不进行删除,很有可能在通过调用B的同时对A进行了操作。也正因为这个原因,这种操作时,必须删除连接后在定义B的相关属性和方法。

(定义很绕嘴,掌握其使用方法即可,简单的定义就是,子函数中的一个属性等于父函数,通过this.函数就可以使用父函数的功能呢,使用完了就删除再做自己该干的事)

例如:

 function B (color){
	this.AB=A;
	this.AB(color);
	delete this.AB;
	this.doors=null;
	this.saydoors=function(){
	alert(this.doors)	
}
}

Call()方法

     call方法是与经典的对象冒充方法最相似的方法.它的第一个参数用作this的对象,其他参数都直接传递给函数自身.


function ClassA(sColor)
{
      this.color = sColor;
      this.sayColor=function()
      {
           alert(this.color);
      }
}
function ClassB(sColor,sName)
{
  
    ClassA.call(this,sColor)
    this.name = sName;
    this.sayName= function()
    {
       alert(this.name);
    }
}
//call
var objB = new ClassB(“red”,”zhang”);
objB.sayColor();   //output “red”
objB.sayName(); //output “zhang”

}apply()方法

apply()方法有两个参数,用作this的对象和要传递给函数的参数的数组.

function ClassA(sColor)
{
      this.color = sColor;
      this.sayColor=function()
      {
           alert(this.color);
      }
}
function ClassB(sColor,sName)
{
    ClassA.apply(this,new Array(sColor));
    this.name = sName;
    this.sayName= function()
    {
       alert(this.name);
    }
}
//call
var objB = new ClassB(“red”,”zhang”);
objB.sayColor();   //output “red”
 objB.sayName(); //output “zhang”

原型链继承

function ClassA(){
}
ClassA.prototype.color = “red”;
ClassA.prototype.sayColor = function(){
     alert(this.color);
}
function ClassB(){
}

//
function ClassB(){
}
ClassB.prototype = new ClassA();
ClassB.prototype.name = “”;
ClassB.prototype.sayName = function(){
          alert(this.name);
} 
//call
var objA = new ClassA();
var objB = new ClassB();
objA.color = "blue";
objB.color = "yellow";
objB.name = "zhang";
objA.sayColor();  //output “blue”
objB.sayColor(); //output “yellow”;
objB.sayName(); //output “zhang”



混合模式

function ClassA(sColor)
{
    this.color = sColor;
}
ClassA.prototype.sayColor = function(){
    alert(this.color);
}
//ClassB
function ClassB(sColor,sName){
     ClassA.call(this,sColor);
     this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function(){
     alert(this.name);
}
//call
var objA = new ClassA(“red”); 
var objB = new ClassB(“blue”,”zhang”); 
objA.sayColor(); //output “red”
objB.sayColor(); //output “blue”
objB.sayName();  //output “zhang”













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值