Skip to content

对象方法

JavaScript 方法(methods)是与对象关联的函数。它们定义了对象可以执行的操作或行为。

方法本质上是一个对象的属性,其值是一个函数(function)。

有几种方法可以在对象上定义方法:

1. 对象字面量中的方法(ES6+ 简写):

Section titled “1. 对象字面量中的方法(ES6+ 简写):”

现代 JavaScript (ES6+) 提供了一种简洁的语法,用于在对象字面量中定义方法。

const person = {
firstName: "John",
lastName: "Doe",
age: 30,
// ES6 method shorthand
fullName() {
return `${this.firstName} ${this.lastName}`;
},
greet() {
console.log(`Hello, my name is ${this.fullName()}.`);
}
};

在这个例子中,fullName 和 greet 是 person 对象的方法。

2. 将传统函数表达式作为属性:

Section titled “2. 将传统函数表达式作为属性:”

在 ES6 之前,或者如果你需要特定的函数类型,你可以将函数表达式赋值给一个属性:

const car = {
brand: "Toyota",
model: "Camry",
displayInfo: function() {
console.log(`Car: ${this.brand} ${this.model}`);
}
};

这两种语法都实现了定义方法的相同结果。出于简洁性考虑,通常首选 ES6 简写。

在用作方法的常规函数(使用 function() 关键字或 ES6 方法简写定义)内部,this 关键字指向调用该方法的对象(即方法调用的“拥有者”)。

在上面的 person.fullName() 示例中,fullName 内部的 this 指向 person 对象。因此,this.firstName 访问的是 person.firstName。

const myObject = {
value: 42,
getValue() {
return this.value; // 'this' refers to myObject
}
};
console.log(myObject.getValue()); // Output: 42

关于箭头函数作为方法的重要注意事项:

如果你使用箭头函数定义方法,this 的行为会不同。箭头函数没有自己的 this 绑定;它们继承自其外部(词法)作用域的 this。这通常意味着 this 不会指向对象本身,这对于需要访问对象属性的方法来说,通常不是你想要的结果。

const counter = {
count: 0,
// Regular function, 'this' is 'counter'
increment() {
this.count++;
console.log(this.count);
},
// Arrow function, 'this' is NOT 'counter'
// 'this' would be the 'this' of the scope where 'counter' is defined (e.g., window or undefined in strict mode)
decrement: () => {
// this.count--; // This would likely cause an error or unexpected behavior
console.log("Cannot use 'this' reliably here for 'counter.count'");
}
};
counter.increment(); // Works as expected
// counter.decrement(); // Would not work as expected for modifying counter.count

对于需要引用对象实例的方法,请使用常规函数语法或 ES6 方法简写,而不要使用箭头函数。

使用点表示法(dot notation)后跟括号 () 来访问(或调用)对象方法:

objectName.methodName()

使用 person 对象的示例:

console.log(person.fullName()); // Invokes fullName(), outputs: "John Doe"
person.greet(); // Invokes greet(), logs the greeting message

如果你访问一个方法属性时没有带括号 (),你将获得函数本身的引用,而不是其执行结果:

const getFullName = person.fullName; // 'getFullName' now holds a reference to the fullName function
console.log(getFullName); // Outputs the function definition: fullName() { ... }
// Calling it later might have 'this' context issues if not bound properly:
// console.log(getFullName()); // 'this' inside getFullName might be undefined or window

你可以随时向现有对象添加新方法:

const book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald"
};
// Adding a new method
book.getDetails = function() {
return `${this.title} by ${this.author}`;
};
console.log(book.getDetails()); // Output: The Great Gatsby by F. Scott Fitzgerald

当创建多个相同类型的对象时,你通常会使用构造函数(constructor function)或 ES6 类(class)。

function PersonConstructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
// Method defined directly on the instance
// This is less memory efficient as each instance gets its own copy of the function
/*
this.sayHello = function() {
console.log(`Hello, I am ${this.firstName}`);
};
*/
// Better: Define methods on the prototype (covered in prototype section)
}
// More efficient to add methods to the prototype:
PersonConstructor.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
const person1 = new PersonConstructor("Alice", "Smith");
console.log(person1.getFullName()); // Output: Alice Smith

ES6 类提供了更清晰的语法来创建对象及其方法。在类中定义的方法会自动添加到原型(prototype)上。

class PersonClass {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Method is automatically on PersonClass.prototype
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
greet() {
console.log(`Greetings from ${this.getFullName()}!`);
}
}
const person2 = new PersonClass("Bob", "Johnson");
console.log(person2.getFullName()); // Output: Bob Johnson
person2.greet(); // Output: Greetings from Bob Johnson!

JavaScript 提供了许多内置对象(如 String、Array、Date、Math),它们都带有自己的实用方法。

此示例使用 String 对象的 toUpperCase() 方法:

const message = “Hello world!”; const upperMessage = message.toUpperCase(); console.log(upperMessage); // Output: HELLO WORLD!

此示例使用 Array 对象的 join() 方法:

const fruits = [“Apple”, “Banana”, “Cherry”]; const fruitString = fruits.join(”, ”); console.log(fruitString); // Output: Apple, Banana, Cherry

方法是面向对象编程的基础。它们允许你将数据(属性)和行为(方法)封装在一个对象内。这使得代码更具组织性、可重用性且更易于管理。

例如,一个 ShoppingCart(购物车)对象可能拥有 addItem()(添加商品)、removeItem()(移除商品)、calculateTotal()(计算总价)等方法,这些方法操作其内部的商品列表及其价格。