JavaScript access object properties and methods

Attribute is a variable used to represent the characteristics of an object, such as color, size, weight, etc.; method is a function used to represent the operation of the object, such as running, breathing, jumping, etc.

The properties and methods of an object are collectively called members of the object.

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.

Create a Person class:

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());  // 使用“.”来访问对象方法

In actual project development, "." is generally used to access object properties; but in some cases, it is convenient to use "[]" Many, for example, JavaScript traverse object properties and methods.

Continuing Learning
||
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <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>
submitReset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!