js中的面向對象的prototype,call的用法

          javascript可以實現面向對象的思想的用法。其中prototype是常見的關鍵字,它的含義可以實際上是“引用”,而非“賦值”。也就是給一個類添加一個屬性或者方法,是給它添加了個引用,而非賦值一份給它。

例子如下:

<script type="text/javascript">
function MyObject(name,size){//方法可以寫爲一個對象的形式
  this.name=name;
  this.size=size;
}
MyObject.prototype.height="2.5m";  //引用對象,並擴展屬性
MyObject.prototype.tellHeight=function(){//引用對象,並擴展方法
  return "height of "+this.name+"is "+this.height;
}
var myobj1= new MyObject("box",3);
if(myobj1.tellHeight){
alert(myobj1.tellHeight());//顯示 height of box is 2.5m
}
</script>

  function MyApplication() {  
    this.counter = 0;  
  }  
          
  MyApplication.prototype.onMapClick = function() {  
      this.counter++;  
      alert("這是您第 " + this.counter + " 次點擊地圖");  
  } 


<script type="text/javascript">
  function ClassA() {  
    alert("a");  
    this.a=function(){alert();};  
  }  
  function ClassB() {  
    alert("b");  
    this.b=function(){alert();};  
  }  
  
  ClassB.prototype.a=new ClassA();        //會導致彈出 a 對話框  
  ClassB.prototype.xx = "xx";  
          
  function initialize() {  
     var objB1=new ClassB();                 //彈出 b 對話框  
     var objB2=new ClassB();                 //彈出 b 對話框  
     alert(objB1.a==objB2.a);                    //true  
     alert(objB1.b==objB2.b);                //false  
     alert("objB1.xx: " + objB1.xx + ", objB2.xx: " + objB2.xx); //objB1.xx: xx, objB2.xx: xx  
     ClassB.prototype.xx = "yy";  
     alert("objB1.xx: " + objB1.xx + ", objB2.xx: " + objB2.xx); //objB1.xx: yy, objB2.xx: yy  
     objB2.xx = "zz";  
     alert("objB1.xx: " + objB1.xx + ", objB2.xx: " + objB2.xx); //objB1.xx: yy, objB2.xx: zz  
 }  
initialize(); 
</script>
prototype、call的用法

<script type="text/javascript">


function baseClass(){
    this.showMsg = function() {
        alert("baseClass::showMsg");   
    }
   
    this.baseShowMsg = function() {
        alert("baseClass::baseShowMsg");
    }
}
baseClass.showMsg = function(){
    alert("baseClass::showMsg static");
}


function extendClass(){
    this.showMsg =function ()  {
        alert("extendClass::showMsg");
    }
}
extendClass.showMsg = function(){
    alert("extendClass::showMsg static")
}


extendClass.prototype = new baseClass();
var instance = new extendClass();


instance.showMsg(); //顯示extendClass::showMsg
instance.baseShowMsg(); //顯示baseClass::baseShowMsg
instance.showMsg(); //顯示extendClass::showMsg


baseClass.showMsg.call(instance);//顯示baseClass::showMsg static


var baseinstance = new baseClass();
baseinstance.showMsg.call(instance);//顯示baseClass::showMsg


</script>

參考:http://blog.csdn.net/xiaoyuemian/article/details/3844305

http://www.cnblogs.com/yjf512/archive/2011/06/03/2071914.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章