在继续本教程之前,请确保您熟悉
JavaScript 方法
JavaScript 方法是定义在对象内的函数。例如,
// dog object
const dog = {
name: "Rocky",
// bark method
bark: function () {
console.log("Woof!");
}
};
// access method
dog.bark();
// Output: Woof!
在上面的示例中,dog 对象有两个键:name 和 bark。
由于 bark 键包含一个函数,我们称之为方法。
请注意,我们使用 dog.bark()
访问了 bark()
方法。因此,访问对象方法的语法是
objectName.methodKey()
JavaScript this 关键字
我们在对象方法中使用 this
关键字来访问同一对象的属性。例如,
// person object
const person = {
name: "John",
age: 30,
// method
introduce: function () {
console.log(`My name is ${this.name} and I'm ${this.age} years old.`);
}
};
// access the introduce() method
person.introduce();
// Output: My name is John and I'm 30 years old.
在上面的示例中,我们创建了具有两个属性(name 和 age)和一个名为 introduce()
的方法的 person 对象。
在 introduce()
方法内部,我们使用 this.name
和 this.age
来引用 person 对象的 name 和 age 键。
要了解更多信息,请访问 JavaScript this。
向对象添加方法
即使在定义之后,您也可以向 JavaScript 对象添加更多方法。例如,
// student object
let student = {
name: "John"
};
// add new method
student.greet = function () {
console.log("Hello");
};
// access greet() method
student.greet();
// Output: Hello
在上面的示例中,我们创建了属性 name: "John"
的 student 对象。
最初,student 没有方法。因此,我们使用点表示法向对象添加了一个新方法
student.greet = function() {
console.log("Hello");
};
JavaScript 内置方法
JavaScript 提供了各种有用的方法,称为内置方法。下表列出了一些常用的内置方法(以及它们所属的相应对象)。
方法 | 对象 | 描述 |
---|---|---|
console.log() | 控制台 | 在浏览器的控制台中显示消息或变量。 |
prompt() |
窗口 | 显示一个对话框,提示用户输入。 |
concat() | 字符串 | 将参数连接到调用字符串。 |
toFixed() | 数字 | 将数字四舍五入为固定的小数位数。 |
sort() | 数组 | 按特定顺序对数组元素进行排序。 |
random() | 数学 | 返回一个介于 0 和 1 之间的伪随机浮点数。 |
要了解有关 JavaScript 内置方法的更多信息,请访问 JavaScript 内置方法。
示例:JavaScript 内置方法
我们使用 concat()
方法连接(连接)两个字符串。例如,
let firstName = "Tony ";
let lastName = "Stark";
// built-in string method concat()
// join lastName to the end of firstName
let fullName = firstName.concat(lastName);
console.log(fullName);
// Output: Tony Stark
在这里,我们使用 concat()
连接了 firstName 和 lastName。
我们使用 toFixed()
方法将数字四舍五入为固定的小数位数。例如,
let num = 5.12345;
// built-in number method toFixed()
// round off num to two decimal places
let roundedNum = num.toFixed(2);
console.log(roundedNum);
// Output: 5.12
在这里,我们使用 toFixed(2)
将 num 的值从 5.12345 四舍五入到 5.12。
另请阅读