Javascript는 객체지향 프로그래밍 언어(OOP, Object-oriencted Programming language)이다.
//object
let Winney = {
_name: 'Winney',
_behavior: 0,
get name() {
return this._name;
},
get behavior() {
return this._behavior;
},
incrementBehavior() {
this._behavior++;
}
}
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior ++;
}
}
const halley = new Dog('Whinney');
console.log(halley.name); // output: 'Whinney'
console.log(halley.behavior); // output: 0
halley.incrementBehavior(); // Add one to behavior
console.log(halley.name); // output: 'Whinney'
console.log(halley.behavior); // ouput: 1
Javascript calls the constructor() method every time it creates a new instance of a class
class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}
dog는 class 이름이다. CamelCase를 사용한다.constructor()를 호출할 때 마다 새로운 dog instance를 생성한다.constructor()는 하나의 argument를 가지고 있다.constructor() 안에 this 키워드를 사용한다. this는 instance name property의 value를 name argument에 적용하는 것에 사용된다.behavior property는 항상 0으로 초기화된다.An instance is an object that contains the property names and methods of a class, but with unique property values.
class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}
const Winney = new Dog('Winney'); // Create new Dog instance
console.log(Winney.name); // Log the name value saved to Winney
// Output: 'Winney'
Dog class 아래에 new keyword를 사용해서 Dog class의 instance가 생성되었다.new keyword는 constructor()를 호출한다.Class method 와 getter 문법은 object과 같지만 그 사이에 comma는 들어가지 않는다.
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
name and behavior.name과 behavior 두 property에 직접적으로 접근해서는 안 되기 때문에 두 property앞에 underscore를 사용함.(_name and _behavior).incrementBehavior 작성함. Dog instance에서 .incrementBehavior를 호출할 때마다 1이 _behavior property에 더해진다.ㅏ : Instance에서 method과 getter를 호출하는 방법은 object에서 method를 호출하는 방법이랑 같다.
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
const halley = new Dog('Whinney');
let nikko = new Dog('Nikko'); // Create dog named Nikko
nikko.incrementBehavior(); // Add 1 to nikko instance's behavior
let bradford = new Dog('Bradford'); // Create dog name Bradford
console.log(nikko.behavior); // Logs 1 to the console
console.log(bradford.behavior); // Logs 0 to the console