JavaScript 中定义方法的方法有:直接在对象中定义方法使用 class 定义方法使用原型定义方法

如何在 JavaScript 中定义方法
直接在对象中定义方法
最简单的方法是在对象中直接定义方法:
<code class="js">const person = {
name: "John",
greet: function () {
console.log(`Hi, my name is ${this.name}!`);
},
};
person.greet(); // Hi, my name is John!</code>使用 class 定义方法
使用 class 关键字定义类时,可以在类中定义方法:
<code class="js">class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hi, my name is ${this.name}!`);
}
}
const person = new Person("John");
person.greet(); // Hi, my name is John!</code>使用原型定义方法
可以通过向原型对象添加方法来定义方法,所有基于该原型的对象都将继承该方法:
<code class="js">const proto = {
greet() {
console.log(`Hi, my name is ${this.name}!`);
},
};
const person1 = Object.create(proto, {
name: {
value: "John",
enumerable: true,
},
});
const person2 = Object.create(proto, {
name: {
value: "Jane",
enumerable: true,
},
});
person1.greet(); // Hi, my name is John!
person2.greet(); // Hi, my name is Jane!</code>以上就是js如何定义方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号