首页 > Web开发 > 详细

js创建对象的几种方式

时间:2015-10-11 21:40:08      阅读:260      评论:0      收藏:0      [点我收藏+]
 //1、使用js内置的对象String/Object/Function
 var str = new String("js内置对象创建对象");
 alert(str);//js内置对象创建对象
 //2、使用Json
 var books = {
  book:[{name:‘设计模式‘},{name:‘Java‘},{name:‘.Net‘}],
  author:[{name:‘cy‘},{name:‘lyl‘},{name:‘cyl‘}]
 }
 //json对象.属性(数组)[1].属性
 //{}里面的字段是属性,[]是数组
 alert(books.book[1].name);//java
 //3、使用自定义对象构造
 //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

js创建对象的几种方式

原文:http://my.oschina.net/u/2472104/blog/515584

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!