이 게시물의 모든 코드는 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 example const 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
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 example const 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'
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 example person.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 example const 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'
위 내용은 객체 생성 - JavaScript 과제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!