用 JavaScript 建立对象的方法有:对象字面量、new 关键字、Object.create() 方法、工厂函数和 Class。

如何用 JavaScript 建立一个对象?
JavaScript 中的对象是一个无序的属性集合,属性包含一个键和一个值。创建一个对象有很多种方法:
1. 对象字面量
这种方法是最简单直接的:
const person = { name: "John Doe", age: 30, occupation: "Software Engineer"};
2. new 关键字
可以使用 new 关键字创建一个对象:
class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; }}const person = new Person("John Doe", 30, "Software Engineer");
3. Object.create() 方法
此方法根据一个现有对象创建一个新对象,新对象的原型指向该现有对象:
const person = { name: "John Doe", age: 30, occupation: "Software Engineer"};const newPerson = Object.create(person);newPerson.name = "Jane Doe";
4. 工厂函数
工厂函数可以用来创建具有相同属性和方法的多个对象:
function createPerson(name, age, occupation) { return { name: name, age: age, occupation: occupation };}const person = createPerson("John Doe", 30, "Software Engineer");
5. Class
ES6 中引入了 class,它是一种语法糖,可以更方便地创建和管理对象:
class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } getName() { return this.name; }}const person = new Person("John Doe", 30, "Software Engineer");
以上就是如何用js建立一个对象的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493949.html
微信扫一扫
支付宝扫一扫