zoukankan      html  css  js  c++  java
  • 引用类型之object类型

    object类型有两种创建方法,第一种是直接创建法:

    var person=new Object();
    person.name = "Nicholas";
    person.age = 29;
    

      


    第二种创建方法使用对象字面量表示法:

    var person={
       name: "Limeng"
       age:20
    }
    

      


    在此有三点说明:
    1.左边花括号意味着表达式字面量的开始,因为它出现在表达式字面量的上下文中,表达式上下文能够返回一个值,在最后一个属性后面不添加逗号。
    2.属性可以使用双引号,使属性名自动转化为字符串。

    var person = {
       "name" : "Nicholas", 
       "age" : 29, 
       5 : true 
    };
    

      


    3.如果大括号为空,那就是一种创建对象的方式。

    //与new Object()相同
    var person = {};
    person.name = "Nicholas";
    person.age = 29;
    

      


    对象字面量创建方法非常常见,因为它给你一种封装函数的感觉,例如:

    function displayInfo(args) {
       var output = "";
    
       if (typeof args.name == "string"){
           output += "Name: " + args.name + "
    ";
       }
    
       if (typeof args.age == "number") {
           output += "Age: " + args.age + "
    ";
       }
    
       alert(output);
    }
    
    displayInfo({
       name: "Nicholas",
       age: 29
    });
    
    displayInfo({
       name: "Greg"
    });
    

      


    使用点来访问对象的属性是非常常见,当然,js也可以使用中括号方法来访问,这个方法是通过变量来访问的,但是注意,在对象字面量创建方法时,应以字符串形式来访问,既要加双引号才行。

    var propertyName = "name";
    //"Nicholas"
    alert(person[propertyName]);
    

      



    当属性名称为保留字或者中间有空格时,使用中括号创建方法是最实用的。

  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/dufemeng/p/4376842.html
Copyright © 2011-2022 走看看