《悟透JavaScript》学习札记七之对象素描

来源:互联网 发布:dota2 知乎话题 编辑:程序博客网 时间:2024/05/01 14:36

     JavaScript对象表示法:JavaScript Object Notation,即JSON。

     1.创建一个没有任何属性的对象: var o = {};

     2.创建一个对象并设置属性及初始值:var person = {name: "Kevin", age: 24, married: false};

     3.创建一个对象并设置属性和方法:var speaker = {text: "Hello world!", say: function(){alert(this.text);}};
                                                        speaker.say(); // output: Hello world!

     4.创建一个更复杂的对象,嵌套其他对象和对象数组等:

         var company =

         {

              name: "Microsoft",

              product: "softwares",

              chairman: {name: "Bill Gates", age: 60},

              employees: [{name: "Kevin", age: 24},{name: "Ben", age: 26}],

              readme: function(){document.write(this.name + " product " + this.product);}

         };

         company.readme(); // output: Microsoft product softwares

        注: JSON 是JavaScript对象最好的序列化形式,比XML更简洁,也更省空间。当需要将JSON字符串变成一个JavaScript对象时,只需要使用eval函数这个强大的数码转换引擎,就立即能得到一个JavaScript内存对象。
原创粉丝点击