JS面向对象开发 (一)对象的创建

来源:互联网 发布:甘肃淘宝馆 编辑:程序博客网 时间:2024/05/05 23:35

<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>123</title>
</style>
</head>
<body>
 
</body>
    <script type="text/javascript" charset='utf-8'>
       
  //object 所有类的基础类  var obj = new object(); || var obj = {};
  
  var obj = {};//实例化对象
  obj.name='chen';//给对象设置属性
  obj.age='23';
  obj.sex='男';
  obj['birthDate']='1992-08-15';//或者中括号设置属性赋值
  obj.sayHello=function(){
alert('hello');
  }
  
  //对象调用自己的属性或方法
  alert(obj.name);
  alert(obj.age);
  obj.sayHello();
  
  //delete:删除对象的属性或方法
  delete obj.age;
  
  //alert(obj.age);
  //输出:undefined
  
  
  //遍历js对象  利用for in 遍历对象 ,输出对象的所有属性  也可遍历数组
  
  for(var attrbute in obj){
//alert(attrbute);//输出 name ,age , sayHello
  }
  
  //取出对象属性以及值
  for(var attrbute in obj){
alert(attrbute +'===='+ obj[attrbute]);//输出 name ,age , sayHello
  }
  
  //对象方法一:
  //constructor保存着用于创建当前对象的函数
  // alert(obj.constructor);  
  // 输出 function object(){
  // [native code]
  //}
  
  var arr = [];
  alert(arr.constructor);//arr是自己的创建对象的方式
  
  //对象方法二:hasOwnProperty
  //   obj.hasOwnProperty('name') 由于存在该属性,返回为true ,否则返回false
  
  // 对象方法三:toString() 返回对象的字符串形式
  alert('obj toString is :'+obj.toString()); //输出 [object Object]
  
  
  // 对象方法四:valueOf() 返回对象的字符串,数值或布尔表示
  
  
    </script>
</html>

0 0
原创粉丝点击