반응형
객체와 클래스
javascript에는 객체를 만드는 여러가지 방법
// Create a user with object literal
var user = {
name: 'Sunny',
interests: ['Traveling', 'Swimming'],
greeting: function () {
console.log('Hi, I\'m ' + this.name + '.');
}
}
user.greeting();// Hi, I'm Sunny.
// Create a constructor function
function User (name, interests) {
this.name = name;
this.interests = interests;
this.greeting = function () {
console.log('Hi, I\'m ' + this.name + '.');
}
}
// Call the constructor with new to create a user object
var user = new User('Sunny', ['Traveling', 'Swimming']);
user.greeting(); // Hi, I'm Sunny.
Object.create() 방법
var user = Object.create(User.prototype, {
name: { value: 'Sunny' },
interests: { value: ['Traveling', 'Swimming']}
});
User.prototype.greeting = function () {
console.log('Hi, I\'m ' + this.name + '.');
}
함수메서드 방법
function createUser (name, interests) {
var user = {};
user.name = name;
user.interests = interests;
user.greeting = function () {
console.log('Hi, I\'m ' + this.name + '.');
};
return user;
}
var user = createUser('Sunny', ['Traveling', 'Swimming']);
user.greeting(); // Hi, I'm Sunny.
ES6 클래스 사용 방법
// Create User class
class User {
// Equivalent to User constructor function
constructor (name, interests) {
this.name = name;
this.interests = interests;
}
// Equivalent to User.prototype.greeting
greeting () {
console.log('Hi, I\'m ' + this.name + '.')
}
}
클래스 expression 방법
// Use class expression
let User = class {
constructor (name, interests) {
this.name = name;
this.interests = interests;
}
greeting () {
console.log('Hi, I\'m ' + this.name + '.')
}
}
반응형
'FRONT-END > JAVASCRIPT' 카테고리의 다른 글
자바스크립트 TDD(Jasmine 단위 테스트) (0) | 2018.01.10 |
---|---|
자바스크립트 표준 #2 (0) | 2018.01.09 |
자바스크립트 표준 #1 (0) | 2018.01.08 |
자바스크립트 HTTP GET 최적화 (1) | 2018.01.08 |
자바스크립트 레이지로드(lazy load) (1) | 2018.01.08 |