JavaScript 对象与方法
发布: (2026年2月4日 GMT+8 13:52)
4 min read
原文: Dev.to
Source: Dev.to
抱歉,我无法直接访问外部链接获取文章内容。请您把需要翻译的文本粘贴到这里,我会帮您翻译成简体中文,并保留原有的格式、Markdown 语法和代码块。
什么是对象中的方法?
方法是存在于对象内部的函数。可以把对象想象成一个工具箱,方法就是里面的工具。
// Object with data and methods (functions inside!)
let person = {
name: "Alice",
age: 25,
sayHello: function() {
console.log("Hello!");
}
};
// Using the method
person.sayHello(); // "Hello!"
Object = Toolbox 🧰
│
├─ Property (data) 📊
├─ Property (data) 📊
├─ Method (function) 🔧
└─ Method (function) 🔧
示例:账户工厂
function createAccount(username, initialBalance) {
let balance = initialBalance;
return {
deposit: function(amount){
balance += amount;
console.log(`Deposited $${amount}. New balance: $${balance}`);
},
withdraw: function(amount){
balance -= amount;
console.log(`Withdrew $${amount}. New balance: $${balance}`);
},
checkBalance: function(){
console.log(`${username}'s balance: $${balance}`);
}
};
}
let account = createAccount("David", 100);
account.deposit(50); // Deposited $50. New balance: $150
account.withdraw(30); // Withdrew $30. New balance: $120
account.checkBalance(); // David's balance: $120
定义方法时
❌ 错误
let obj = {
method(): function() { } // Syntax error!
};
✅ 正确
let obj = {
method: function() { } // Good!
};
this 关键字
方法可以使用 this 访问同一对象中的其他属性:
let person = {
name: "David",
age: 25,
introduce() {
console.log(`Hi! I'm ${this.name} and I'm ${this.age} years old.`);
},
birthday() {
this.age++;
console.log(`Happy birthday! I'm now ${this.age}!`);
}
};
person.introduce(); // Hi! I'm David and I'm 25 years old.
person.birthday(); // Happy birthday! I'm now 26!
person.introduce(); // Hi! I'm David and I'm 26 years old.
将相关函数分组在一起
混乱(分散的函数)
function addNumbers(a, b) { return a + b; }
function subtractNumbers(a, b) { return a - b; }
function multiplyNumbers(a, b) { return a * b; }
整洁(带方法的对象)
let math = {
add(a, b) { return a + b; },
subtract(a, b) { return a - b; },
multiply(a, b) { return a * b; }
};
math.add(5, 3); // 8
创建多个实例
function createDog(name) {
return {
bark: function() {
console.log(`${name} says: Woof!`);
}
};
}
let dog1 = createDog("Buddy");
let dog2 = createDog("Max");
dog1.bark(); // Buddy says: Woof!
dog2.bark(); // Max says: Woof!
使用闭包保持数据私有
function createPassword(pwd) {
let password = pwd; // Private variable!
return {
check: function(attempt) {
return attempt === password;
},
change: function(oldPwd, newPwd) {
if (oldPwd === password) {
password = newPwd;
return "Password changed!";
}
return "Wrong password!";
}
};
}
let myPassword = createPassword("secret123");
console.log(myPassword.password); // undefined
console.log(myPassword.check("secret123")); // true
console.log(myPassword.change("secret123", "newPass")); // Password changed!
对象方法 vs. 普通函数
let calculator = {
add: function(a, b) {
return a + b;
}
};
calculator.add(2, 3); // 5 (must call via object)
function add(a, b) {
return a + b;
}
add(2, 3); // 5 (called directly)
当函数相互关联且属于同一组时,使用对象方法。
编写方法的三种方式
1️⃣ 传统写法
let calculator = {
add: function(a, b) {
return a + b;
}
};
2️⃣ 简写(现代 – 推荐)
let calculator = {
add(a, b) {
return a + b;
}
};
3️⃣ 箭头函数
let calculator = {
add: (a, b) => {
return a + b;
}
};
调用方法
let obj = {
method() {
console.log("Called!");
}
};
obj.method; // Returns the function (does not call it)
obj.method(); // Calls the function ✓
祝编码愉快!