js建立對象的幾種方式

 //一、使用js內置的對象String/Object/Function
 var str = new String("js內置對象建立對象");
 alert(str);//js內置對象建立對象
 //二、使用Json
 var books = {
  book:[{name:'設計模式'},{name:'Java'},{name:'.Net'}],
  author:[{name:'cy'},{name:'lyl'},{name:'cyl'}]
 }
 //json對象.屬性(數組)[1].屬性
 //{}裏面的字段是屬性,[]是數組
 alert(books.book[1].name);//java
 //三、使用自定義對象構造
 //javascript中的每一個對象都有prototype屬性,Javascript中對象的prototype屬性的解釋是:返回對象類型原型的引用。
 //3 eg1
 function Girl(){
  this.name = 'cy';
  this.age = 22;
  this.tel = '13026167827';
 }
 function Gril(){
  Gril.prototype.name = 'lyl';
  Gril.prototype.age = 20;
  Gril.prototype.tel;
 }
 var gril = new Gril();
 alert(gril.age);//lyl
 //3 eg2
 function Test(){
  this.test = function(){
   alert('defined by this'); 
  }
 }
 Test.prototype.test = function(){
  alert('defined by prototype'); 
 }
 var fun = new Test();
 fun.test();//defined by this
 //3 eg3
 //基類中兩個方法
 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")
 }
 
 //原型類,至關於j實例化ava中的繼承類
 extendClass.prototype = new baseClass();
 //繼承類,至關於直接實例化實現類
 var instance = new extendClass();
 instance.showMsg(); //顯示extendClass::showMsg
 //不存在,就去prototype,也就是基類中找
 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
相關文章
相關標籤/搜索