-
ClassesJavaScript 2021. 12. 10. 11:30
JavaScript의 Class에 대한 개념 및 문법을 정리하기 위해 작성하였습니다.< Introduction To Classes >
Classes are a tool to quickly produce similar objects and template for objects.
< Constructor >
To create a new instance of a class.
It sets the property value for each instance.Example)
class Dog { constructor(name) { this.name = name; this.behavior = 0; } }
: By convention, we capitalize and CamelCase class names.
: In the context of a class, this refers to an instace of that class.
< Instance >
An instance is an object that contains the property names and methods of a class, but with unique property values.
Use new keyword to generate new instance, It calls the constructor( ), runs the code inside of it. and then returns new instance.Example)
class Dog { constructor(name) { this.name = name; this.behavior = 0; } } const halley = new Dog('Halley'); // Create new Dog instance console.log(halley.name); // Log the name value saved to halley // Output: 'Halley'
< Methods >
Class method syntax is the same as it is for objects except you can not include commas between methods.
Example)
class Dog { constructor(name) { this._name = name; this._behavior = 0; } get name() { return this._name; } get behavior() { return this._behavior; } incrementBehavior() { this._behavior++; } }
< Inheritance >
With inheritance, you can create a parent class (also known as a superclass) with properties and methods that multiple child classes (also known as subclasses) share.
The child classes inherit the properties and methods from their parent class.< How to use Inheritance >
1. use extends keyword : makes the methods of the parent class available inside the child classes.
2. Super keyword : calls the constructor ( ) of a parent class.class SubClass extends SuperClass { // ~~~ }
- you must always call the 'super' method before use 'this' keyword. (if you don't, reference error)
3. Child classes can contain their own properties, methods.class SubClass extends SuperClass { constructor(prop1, prop2) { super(prop1); this.property = prop2; } }
Example)
class Animal { constructor(name) { this._name = name; this._behavior = 0; } get name() { return this._name; } get behavior() { return this._behavior; } incrementBehavior() { this._behavior++; } } class Cat extends Animal { constructor(name, usesLitter) { super(name); this._usesLitter = usesLitter; } get usesLitter() { return this._usesLitter; } }
: The child classes inherit the properties and methods from their prarent class.
< Static Methods >
Static methods are available on the class, but not on instances of the class using static keyword.
Example)
class Animal { constructor(name) { this._name = name; this._behavior = 0; } static generateName() { const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara']; const randomNumber = Math.floor(Math.random()*5); return names[randomNumber]; } } console.log(Animal.generateName()); // returns a name const tyson = new Animal('Tyson'); tyson.generateName(); // TypeError
< Prototype >
프로토타입 이란 클래스의 원형객체를 의미합니다.
클래스에서 객체로 상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있습니다.
JavaScript는 흔히 프로토타입 기반 언어(prototype-based language)라 불립니다.
— 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다는 의미입니다. 프로토타입 객체도 또 다시 상위 프로토타입 객체로부터 메소드와 속성을 상속 받을 수도 있고 그 상위 프로토타입 객체도 마찬가지입니다. 이를 프로토타입 체인(prototype chain)이라 부르며 다른 객체에 정의된 메소드와 속성을 한 객체에서 사용할 수 있도록 하는 근간입니다.- Class와 Prototype과 Instance(object)의 관계
Example)
class Human { constructor(name, age) { this.name = name; this.age = age; } sleep() { console.log(`${this.name}은 잠에 들었습니다`); } } let kimcoding = new Human('김코딩', 30); Human.prototype.constructor === Human; // true Human.prototype === kimcoding.__proto__; // true Human.prototype.sleep === kimcoding.sleep; // true
Reference : Object prototypes
Object prototypes - Web 개발 학습하기 | MDN
Javascript에서는 객체를 상속하기 위하여 프로토타입이라는 방식을 사용합니다. 본 문서에서는 프로토타입 체인이 동작하는 방식을 설명하고 이미 존재하는 생성자에 메소드를 추가하기 위해
developer.mozilla.org
'JavaScript' 카테고리의 다른 글
Error Handling (0) 2021.12.11 Modules (0) 2021.12.11 Data type (0) 2021.10.25 Higher-Order Functions (0) 2021.10.19 Objects (2) (0) 2021.10.17