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

来源:互联网 发布:淘宝沟通服务 编辑:程序博客网 时间:2024/05/21 16:40

          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

0 0