JavaScript 对象声明以及对象所有方法
对象声明
在JavaScript中,对象可以通过以下几种方式声明:
- 字面量方式
var obj = {
key1: value1,
key2: value2,
};
示例:
var person = {
name: "John",
age: 30,
city: "New York"
};
- 构造函数方式
function Obj() {
this.key1 = value1;
this.key2 = value2;
...
}
var obj = new Obj();
示例:
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
var person = new Person("John", 30, "New York");
对象方法
JavaScript对象可以拥有自己的方法(函数)。下面是一些常用的对象方法:
方法声明
- 字面量方式
var obj = {
key1: value1,
key2: value2,
method1: function() {
// 方法体
},
method2: function() {
// 方法体
},
...
};
示例:
var person = {
name: "John",
age: 30,
introduce: function() {
console.log("My name is " + this.name + ", I'm " + this.age + " years old.");
}
};
- 构造函数方式
function Obj() {
this.key1 = value1;
this.key2 = value2;
this.method1 = function() {
// 方法体
};
this.method2 = function() {
// 方法体
};
...
}
var obj = new Obj();
示例:
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
this.introduce = function() {
console.log("My name is " + this.name + ", I'm " + this.age + " years old.");
};
}
var person = new Person("John", 30, "New York");
方法调用
可以通过对象访问方法并调用:
obj.method1();
示例:
person.introduce();
示例
var person = {
name: "John",
age: 30,
city: "New York",
introduce: function() {
console.log("My name is " + this.name + ", I'm " + this.age + " years old, living in " + this.city + ".");
},
increaseAge: function() {
this.age++;
}
};
person.introduce(); // 输出:My name is John, I'm 30 years old, living in New York.
person.increaseAge();
person.introduce(); // 输出:My name is John, I'm 31 years old, living in New York.