JavaScript obje...LOGIN

JavaScript object literal

In JavaScript, objects can be created through class instantiation, or objects can be created directly using object literals.

In programming languages, literals are a notation for representing values. For example, "Hello, World!" represents a string literal in many languages. JavaScript is no exception, such as 5, true, false and null, which respectively represent an integer, two Boolean values ​​and an empty object.

JavaScript supports object literals, allowing objects to be created using a concise and readable notation.

An object literal is a list of name/value pairs, each name/value pair is separated by commas and finally enclosed in curly brackets. A name/value pair represents a property or method of an object, with the name and value separated by a colon.

For example:

var  myCar={
        "price" : ",000" ,   // 属性
        "color" : "red" ,   // 属性
        "run" : function(){ return " 120 km/h "; }   // 方法
    }
var myHome={
        population : "10,000" ,
        area : "10,000" ,
        adress : {  // 属性
                country : "China" ,
                province : "shanxi" ,
                city : "xian"
            },
        say : function(){  // 方法
                return "My hometown is very beautiful ! ";
            }
    }

Create a zhangsan object:

var zhangsan={
    name : "张三",
    sex : "男",
    say:function(){
        return "嗨!大家好,我来了。";
    },
    contact : {
        tel : "029-81895644",
        qq : "1370753465",
        email : "it@gmail.com"
    }
}
alert("姓名:"+zhangsan.name);
alert("性别:"+zhangsan.sex);
alert(zhangsan.say());
alert("电话:"+zhangsan.contact.tel);
alert("QQ:"+zhangsan.contact.qq);
alert("邮箱:"+zhangsan.contact.email);

You can see:

  • Use object literals to create a single Object,semantics are intuitive.

  • Object literals can be nested.


#Object literals can also be created first and then add properties and methods.

The zhangsan object above can also be created like this:

var zhangsan={}
zhangsan.name = "张三";
zhangsan.sex = "男";
zhangsan.say = function(){
        return "嗨!大家好,我来了。";
    }
zhangsan.contact = {
    tel : "029-81895644",
    qq : "1370753465",
    email : "it@gmail.com"
}


Next Section
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script>var zhangsan={ name : "张三", sex : "男", say:function(){ return "嗨!大家好,我来了。"; }, contact : { tel : "029-81895644", qq : "1370753465", email : "it@gmail.com" } } alert("姓名:"+zhangsan.name); alert("性别:"+zhangsan.sex); alert(zhangsan.say()); alert("电话:"+zhangsan.contact.tel); alert("QQ:"+zhangsan.contact.qq); alert("邮箱:"+zhangsan.contact.email);</script> </head> <body> </body> </html>
submitReset Code
ChapterCourseware