<script type="text/javascript"> // 使用工厂方式(原始方式)创建对象 var ob = new Object; // 创建对象 ob.name = 'zhangsan'; // 声明对象属性 ob.age = 20; ob.gender = '男'; ob.getInfo = function(){ // 声明对象方法 return '姓名:' + this.name + ',性别:' + this.gender + ',年龄' + this.age; } // 使用对象 document.write(ob.name + '<br/>'); // 输出结果:zhangsan document.write(ob.gender + '<br/>'); // 输出结果:男 document.write(ob.age + '<br/>'); // 输出结果:20 document.write(ob.getInfo() + '<br/>'); // 输出结果:姓名:zhangsan,性别:男,年龄20 </script>
使用函数将对象包裹起来
<script type="text/javascript"> // 使用函数包裹起来创建对象 function Person(){ var ob = new Object; // 创建对象 ob.name = 'zhangsan'; // 声明对象属性 ob.age = 20; ob.gender = '男'; ob.getInfo = function(){ // 声明对象方法 return '姓名:' + this.name + ',性别:' + this.gender + ',年龄' + this.age; } return ob; } var p = Person(); // 使用对象 document.write(p.name + '<br/>'); document.write(p.gender + '<br/>'); document.write(p.age + '<br/>'); document.write(p.getInfo() + '<br/>'); </script>
<script type="text/javascript"> // 使用构造方式创建对象 function Person(name,age,gender){ this.name = name; // 声明对象属性 this.age = age; this.gender = gender; this.getInfo = function(){ // 声明对象方法 return '姓名:' + this.name + ',性别:' + this.gender + ',年龄' + this.age; } } var p = new Person('张三',18,'男'); // 使用对象 document.write(p.name + '<br/>'); document.write(p.gender + '<br/>'); document.write(p.age + '<br/>'); document.write(p.getInfo() + '<br/>'); </script>
<script type="text/javascript"> // 快速创建对象 var p = { name:'张三', age:20, gender:'男', getInfo:function(){ return this.name + ',' + this.gender + ',' + this.age; } } // 使用对象 document.write(p.name + '<br/>'); document.write(p.gender + '<br/>'); document.write(p.age + '<br/>'); document.write(p.getInfo() + '<br/>'); </script>
<?php $stu = array( array('name'=>'张三','age'=>20,'gender'=>'男'), array('name'=>'李四','age'=>21,'gender'=>'男'), array('name'=>'王五','age'=>22,'gender'=>'男'), array('name'=>'马六','age'=>23,'gender'=>'男') ); echo json_encode($stu); // 输出结果为 /* [{"name":"\u5f20\u4e09","age":20,"gender":"\u7537"},{"name":"\u674e\u56db","age":21,"gender":"\u7537"},{"name":"\u738b\u4e94","age":22,"gender":"\u7537"},{"name":"\u9a6c\u516d","age":23,"gender":"\u7537"}] */
<script type="text/javascript"> // 快速创建对象 var str = '[{"name":"\u5f20\u4e09","age":20,"gender":"\u7537"},{"name":"\u674e\u56db","age":21,"gender":"\u7537"},{"name":"\u738b\u4e94","age":22,"gender":"\u7537"},{"name":"\u9a6c\u516d","age":23,"gender":"\u7537"}]'; /*for(var i=0;i<str.length;i++){ document.write(str[i].name+'<br/>'); }*/ eval("var stu="+str+";"); for(var i=0;i<stu.length;i++){ document.write(stu[i].name+','+stu[i].age+','+stu[i].gender+'<br/>'); } </script> 输出结果: 张三,20,男 李四,21,男 王五,22,男 马六,23,男