面向对象基础(2)

学继承之前先讲一下什么是引用。

引用:

 var arr2=arr1; //实际上只是把arr2指向了arr1
        arr2.push(4);
        alert(arr2); //1234
        alert(arr1);  //应该是123,但也弹出1234



//斛决引用问题
var arr1=[1,2,3];
        //var arr2=arr1;
        var arr2=[];
        for(var i=0;i<arr1.length;i++)
        {
            arr2.push(arr1[i]);
        }
        arr2.push(4);
        alert(arr2); //1234
        alert(arr1);  //123

 

call:通过call的方式调用属性时,如果call传入的参数,则参数会替换掉函数中的this;

function show(a,b){
            alert('this是' + this +'\na是:'+ a + '\nb是'+ b);
        }
        //show(12,1);
        show.call(12,2,1);
        //show.call(this);

所以

继承:

  对象由:属性和方法组成;

   继承:继承父类的属性和方法;

//有引用问题的  
 //父类
     function CreatePerson()
   {
         this.name="wangyu"
     }
     CreatePerson.prototype.showName=function()
   {
        alert(this.name);
     }
        
    //子类,让他去继承父元素的属性和方法
    function CreateChild(){
        CreatePerson.call(this);  //继承父元素属性
    }
        CreateChild.prototype=CreatePerson.prototype;//继承父元素方法 注意顺序(有引用问题的)
        
        var obj=new CreateChild();

        obj.showName();
———————————————————————————————————————————————————————————————————————————————————————
//解决引用问题   //父类 function CreatePerson()
{
this.name="wangyu" } CreatePerson.prototype.showName=function()
{ alert(
this.name); } //子类,让他去继承父元素的属性和方法 function CreateChild(){ CreatePerson.call(this); //继承父元素属性 } for(var i in CreatePerson.prototype){ CreateChild.prototype[i]=CreatePerson.prototype[i] }
   var obj=new CreateChild();
    obj.showName();
 

写一个继承的例子:

       //父类
        function Fruits(color){
            this.color=color;
        }
        Fruits.prototype.ShowColor=function(){
            alert(this.color);
        }
            
         //子类Apple
         function Apple(color){
             Fruits.call(this,color);  //继承属性
             //Fruits.apply(this,[color]); //也可以这么写用apply
         }
    
        //子类Bannan
         function Banana(color){
             Fruits.call(this,color);  //继承属性
             //Fruits.apply(this,[color]);//也可以这么写用apply
         }
         
         for(var i in Fruits.prototype)//继承方法
         {
             Apple.prototype[i]=Fruits.prototype[i];
             Banana.prototype[i]=Fruits.prototype[i];
         }
         
         var objB=new Apple("red");
         var objC=new Banana("yellow");
        
         objB.ShowColor();
         objC.ShowColor();

总结:属性的继承利用call,方法的继承利用循环;

猜你喜欢

转载自www.cnblogs.com/sun927/p/9342634.html