Access object properties and methods

Accessing the properties of an object

In JavaScript, you can use "." and "[]" to access the properties of an object.

1. Use "." to access object properties
Syntax:

    objectName.propertyName


Where objectName is the object name and propertyName is the property name.

2. Use "[ ]" to access object properties
Syntax:

    objectName[propertyName]


Where objectName is the object name and propertyName is the property name.

Methods to access objects

In JavaScript, you can only use "." to access methods of objects.

Syntax:

    objectName.methodName()


Among them, objectName is the object name and methodName() is the function name.

Example: Create a Person class:

<html>
<head>
    <script>
        function Person() {
            this.name=" 张三 ";  // 定义一个属性 name
            this.sex=" 男 ";  // 定义一个属性 sex
            this.age=22;  // 定义一个属性 age
            this.say=function(){  // 定义一个方法 say()
                return "嗨!大家好,我的名字是 " + this.name + " ,性别是 " + this.sex + ",今年 " + this.age +"岁!";
            }
        }
        var zhangsan=new Person();
        alert("姓名:"+zhangsan.name);  // 使用“.”来访问对象属性
        alert("性别:"+zhangsan.sex);
        alert("年龄:"+zhangsan["age"]);  // 使用“[ ]”来访问对象属性
        alert(zhangsan.say());   // 使用“.”来访问对象方法
    </script>
</head>
<body>
</body>
</html>


Continuing Learning
||
<html><span style="font-size:18px;"> <head> <script language="javascript"> function Person() {}; var p1 = new Person(); p1.name = "拉拉"; window.alert(p1.name); var al = "na" + "me"; window.alert(p1[al]); </script> </head> <body> </body> </span> </html>
submitReset Code