티스토리 뷰

JavaScript & TypeScript

5. class vs object

kingsubin 2020. 11. 14. 11:06

 

class

  • template
  • declare once
  • no data in
  • introduced in ES6
  • syntactical sugar over prototype-based inheritance

 

1. class declarations

class Person {
	// constructor
	constructor (name, age) {
		// fields
		this.name = name;
		this.age = age;
	}
	
	// methods
	speak() {
		console.log(`${this.name}: hello! `);
	}
}

const ellie = new Person('ellie', 20);
console.log(ellie.name); // ellie
console.log(ellie.age); // 20
ellie.speak(); // ellie: hello!

 

 

2. Getter and setters

class User {
	constructor(firstName, lastName, age) {
		this.firstName = firstName;
		this.lastName= lastName;
		this.age= age;
	}

	get age() {
		return this._age;
	}

	set age(value) {
		this._age = value < 0 ? 0 : value;
	}
}

const user1 = new User('Steve', 'Job', -1);
console.log(user1.age); // 0

 

 

3. Fields (public, private)

  • Too soon ! 
class Experiment {
	publicField = 2;
	#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment .publicField); // 2
console.log(experiment .privateField); // undefined

 

 

 

4. Static properties and methods

  • Too soon !
class Article {
	static publisher = 'Dream Coding';
	constructor(articleNumber) {
		this.articleNumber = articleNumber;
	}

	static printPublisher() {
		console.log(Article.publisher);
	}
}

const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher); // Dream Coding
Article.printPublisher(); // Dream Coding

 

 

5. Inheritance

  • a way for one class to extend another class
class Shape {
	constructor (width, height, color) {
		this.width = width;
		this.height= height;
		this.color= color;
	}

	draw() {
		console.log(`drawing ${this.color} color!`);
	}
	
	getArea() {
		return this.width * this.height;
	}
}

class Rectangle extends Shape {} 
class Triangle extends Shape {
	draw() {
		super.draw(); // drawing this.color color !
		console.log('tri'); // tri
	}
	getArea() {
		return (this.width * this.height) / 2;
	}
} 

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea()); // 400
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
console.log(triangle.getArea()); // 200

 

 

6. Class checking : instanceof

console.log(rectangle instanceof Rectangle); // t
console.log(triangle instanceof Rectangle); // f
console.log(triangle instanceof Triangle); // t
console.log(triangle instanceof Shape); // t
console.log(triangle instanceof Object); // t
console.log(triangle.toString()); 

 

 

 


Object

  • instance of a class
  • created many times
  • data in

 

 

 


※출처

www.youtube.com/channel/UC_4u-bXaba7yrRz_6x6kb_w

'JavaScript & TypeScript' 카테고리의 다른 글

7. Array, API  (0) 2020.11.14
6. what is object  (0) 2020.11.14
4. Arrow Function  (0) 2020.11.13
3. operator, if, for loop  (0) 2020.11.13
2. data types, let vs var, hoisting  (0) 2020.11.13