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
相关文章
相关标签/搜索