
您可以在 repo github 上找到这篇文章中的所有代码。
对象创建方法
基于构造函数
es6之前推荐。
/** * @param {string} firstname * @param {string} lastname * @param {number} age */function person(firstname, lastname, age) { this.firstname = firstname; this.lastname = lastname; this.age = age; this.greet = function () { console.log(`hello, my name is ${this.firstname} ${this.lastname}`); };}// usage exampleconst person1 = new person("john", "doe", 30);person1.greet(); // => hello, my name is john doeconst person2 = new person("jane", "smith", 25);person2.greet(); // => hello, my name is jane smith
基于类别
es6 之后推荐。
class person { constructor(firstname, lastname, age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } greet() { console.log(`hello, my name is ${this.firstname} ${this.lastname}`); }}// usage exampleconst person1 = new person("john", "doe", 30);person1.greet(); // => 'hello, my name is john doe'const person2 = new person("jane", "smith", 25);person2.greet(); // => 'hello, my name is jane smith'
对象初始值设定项
const person = { firstname: "john", lastname: "doe", age: 30, greet: function () { console.log(`hello, my name is ${this.firstname} ${this.lastname}`); },};person.greet(); // => 'hello, my name is john doe'
对象.create()
const personprototype = { greet: function () { console.log(`hello, my name is ${this.firstname} ${this.lastname}`); },};const person = object.create(personprototype);person.firstname = "john";person.lastname = "doe";// usage exampleperson.greet(); // => 'hello, my name is john doe'
工厂模式
/** * @param {string} firstName * @param {string} lastName * @param {number} age * @return {object} */function createPerson(firstName, lastName, age) { return { firstName: firstName, lastName: lastName, age: age, greet: function () { console.log(`Hello, my name is ${this.firstName} ${this.lastName}`); }, };}// Usage exampleconst person1 = createPerson("John", "Doe", 30);person1.greet(); // => 'Hello, my name is John Doe'const person2 = createPerson("Jane", "Smith", 25);person2.greet(); // => 'Hello, my name is Jane Smith'
参考
类 – mdn面向对象编程 – mdn面向对象编程 – mdn对象初始值设定项 – mdnobject.create() – mdn工厂模式-patterns.dev
以上就是对象创建 – JavaScript 挑战的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1495293.html
微信扫一扫
支付宝扫一扫