当前位置: 代码迷 >> JavaScript >> 写了几种创办JS对象的例子
  详细解决方案

写了几种创办JS对象的例子

热度:240   发布时间:2012-11-10 10:48:51.0
写了几种创建JS对象的例子
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
<script type="text/javascript">
////////////////构造函数方式///////////////////////////////////
function myClass() {
            this.id = 5;
            this.name = 'myclass';
            this.getName = function() {
                return this.name;
            }
        }
var my = new myClass();
alert(my.id);
alert(my.getName());

//////////////////混合的构造函数/原型方式//////////////////////////////
function Car(sColor, iDoors, iMpg) {  
    this.color = sColor;  
    this.doors = iDoors;  
    this.mpg = iMpg;  
    this.drivers = new Array("Mike", "Sue");  
}  
 
Car.prototype.showColor = function () {
    alert(this.color+this.doors);
};  

Car.prototype.getValue = function(){
return this.color;
};
var oCar1 = new Car("red", 4, 23);  
var oCar2 = new Car("blue", 3, 25);  
 
oCar1.drivers.push("Matt");

alert(oCar1.drivers);    //outputs "Mike,Sue,Matt"  
alert(oCar2.drivers);    //outputs "Mike,Sue"
document.write(oCar1.getValue()+':');
////////////////////////////////////////////////////
function StringBuffer(){
this.strings = new Array;
}
StringBuffer.prototype.append=function (str){
this.strings.push(str);
};
StringBuffer.prototype.toString = function(){
return this.strings.join("");
};
var sb = new StringBuffer();
sb.append('aaaa');
sb.append('aaa1111a');
document.write(sb.toString());
///////////////动态原型方法//////////////////////////////////////////
function Bus(sColor,iDoors,iMpg) {  
  this.color = sColor;  
  this.doors = iDoors;  
  this.mpg = iMpg;  
  this.drivers = new Array("Mike","John");  
    
  if (typeof Bus._initialized == "undefined") {  
    Bus.prototype.showColor = function() {  
     alert(this.color);  
    };  
     Bus.prototype.getValue = function(){
   return 'Bus:'+this.color;
  };
    Bus._initialized = true;  
  }  
}

var bus = new Bus('red',4,'mpg');
alert(bus.getValue());
</script>
</HEAD>

<BODY>
<a href="javascript:if(confirm('要删除吗?'))">删除</a>
</BODY>
</HTML>
1 楼 tobestronger123 2012-04-13  
if (typeof Bus._initialized == "undefined") 这句话是初始化的意思吗?以前没有见过这种写法,楼主能说明一下typeof Bus._initialized 的用法吗?谢谢了!
  相关解决方案