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=" 張三 "; // 定義一個(gè)屬性 name this.sex=" 男 "; // 定義一個(gè)屬性 sex this.age=22; // 定義一個(gè)屬性 age this.say=function(){ // 定義一個(gè)方法 say() return "嗨!大家好,我的名字是 " + this.name + " ,性別是 " + this.sex + ",今年 " + this.age +"歲!"; } } var zhangsan=new Person(); alert("姓名:"+zhangsan.name); // 使用“.”來(lái)訪問對(duì)象屬性 alert("性別:"+zhangsan.sex); alert("年齡:"+zhangsan["age"]); // 使用“[ ]”來(lái)訪問對(duì)象屬性 alert(zhangsan.say()); // 使用“.”來(lái)訪問對(duì)象方法 </script> </head> <body> </body> </html>