JavaScript 对象方法
JavaScript 对象是属性和方法的集合,方法定义了对象上能进行的操作。
JavaScript 对象是属性和方法的集合,方法定义了对象上能进行的操作。
例如:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
this 关键字
在函数定义中, this
指的是函数的“所有者”。
在对象的方法中,this
指的是当前对象本身,可以通过 this
调用当前对象的属性和方法。
在上面的示例中, this.firstName
返回的是当前对象的 firstName
属性。
要了解更多关于 this 的信息,请访问 JavaScript this 关键字章节。
JavaScript 方法
JavaScript 对象的方法是可以对对象执行的操作,对象的方法是特殊的属性,属性的值为函数。
属性名 | 属性值 |
---|---|
firstName |
John |
lastName |
Doe |
age |
50 |
eyeColor |
blue |
fullName |
function() {return this.firstName + " " + this.lastName;} |
person 对象的 fullName
方法的属性名(方法名)为 fullName
, 属性值为函数。
调用对象方法
您可以使用以下语法访问对象方法:
objectName.methodName();
通常将 fullName()
描述为 person 对象的方法,将 fullName
描述为属性。
此示例调用 person 对象的 fullName() 方法:
name = person.fullName();
如果您访问对象方法的时候忘记了带 ()
,它将返回函数定义:
name = person.fullName;
向对象添加方法
向对象添加新方法很容易:
person.name = function () {
return this.firstName + " " + this.lastName;
};
使用内置方法
此示例使用 String 对象的 toUpperCase()
方法将文本转换为大写:
let message = "Hello world!";
let x = message.toUpperCase();
执行上述代码后,x 的值将是: HELLO WORLD!
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};