JS | Object, class

yeeun lee·2020년 7월 1일
1

Javascript

목록 보기
4/4

1. Object

collections of related data and functionality.

1.1 객체

python의 dictionary 개념인 것 같다. { } 를 사용하고 순서 없이 넣는다. Key-value pairs (=property)로 이루어져 있다.
property가 함수면 method 라고 부른다.

let spaceship = {'Fuel Type': ‘diesel', color: ‘silver'};

- 객체 속성에 접근

  • dot notation ‘.’
  • bracket notation [ ]

Square bracket은 숫자, 스페이스가 있는 단어, 특별한 캐릭터가 있을 때 사용한다.
const로 객체를 선언해도, 바꾸거나 추가할 수 있다.

- 객체 속성 추가

Object = {prop : value}
Object.prop = value (** let 쓰지 않음)

객체에 메소드를 추가하는 방법 key는 method의 이름, value는 코드블럭으로 구성
Object = { method1 ( ) { } , ,method2 ( ) { } }

- nested object

object 안에 object, 또 그 안에 object ! 객체가 다른 객체를 속성으로서 가질 수 있다.

? Objects are passed by reference— when we make changes to an object passed into a function, those changes are permanent. 이해 안 감 …

- Loop

객체의 속성을 지나는 반복문을 만들 수 있다.

for (let crewMember in spaceship.crew) {
  console.log(`${spaceship.crew[crewMember].name} : ${spaceship.crew[crewMember].degree}`)
} 

1.2 property & method 의 차이점

Property is what an object has, and method is what an object does.

1.3 Advanced Object

- this(=Calling object)

객체의 property 간에는 다이렉트로 접근이 불가해서 나온 키워드. 부르는 객체의 속성에 접근할 수 있도록 한다.

arrow function은 this 쓸 수 없다! * Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object

- privacy in objects

오직 특정한 속성만 mutable 하거나 value 를 바꿀 수 있다. javascript는 privacy built-in language가 아니다. 다만 개발자 간의 컨벤션이 있음!
언더바: property should not be altered.

- getters & setters

객체의 내부 속성 관련 메소드. ()로 부를 필요 없다. 속성 부르는 것처럼! 그렇기 때문에 속성이랑 같은 내용으로 만들면 안 됨 .
This, 조건문 사용 가능.
속성을 객체 외부에서 불러올 때는 꼭 언더바를 붙이고, getter, setter 사용할 때에는 언더바를 붙이지 않는다.

  • getters: 속성의 값을 얻어온다. gets and return
  • setters: 속성의 값을 설정한다. Reassign. 반환값은 거쳐간 value 이므로 Return 안 써도 됨.

1.4 factory function

객체를 반환하고 여러 객체의 요소로 재사용될 수 있는 함수. 파라미터를 가짐!

some shorthand

property value shorthand : destructing (변수에 속성을 assign 하는 새로운 단축키) key와 value 가 똑같을 경우 두 번 입력하는 수고를 덜기 위해 property value shorthand 를 만듦

const cat = (name, age) => {
return { name: name,  age: age} }

destructured assignment : {value} = key
nested property의 경우 그 전 부분까지는 호출해야 함. 예를들어 robot > functionality > beep() 순이라면
Const {beep} = robot.functionality *** functionality.beep() 해야 호출됨.

정리

호출한 객체: 메소드가 속한 객체를 calling object 라고 함 Keyword this 가 calling object 를 가르키고 속성에 접근할 때 사용함.

  • Calling object의 다른 내부 속성에 자동적으로 접근할 수 없음
  • 다른 내부 속성에 접근하려면 arrow function 사용할 수 없음

2. Class

template for objects

class

tool that developers use to quickly produce similar objects. serves as a template for creating new Dog objects. Class name은 capitalize, camelcase 하는 것이 컨벤션

-object syntax와 다른 점

  • constructor method : class의 new instance를 만들 때마다 불러짐. 만들 때는 ‘new' keyword 사용
    this 키워드를 사용하고, 여기서 this 는 class의 instance를 지칭함
  • Method 사용 시 주의점:  you can not include commas between methods.

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.

- Extends

Class child extends parent {}

- Super

super(argument) -> constructor of parent class . This keyword 전에 사용해야 함. 가장 첫번째로 사용하는 것이 에러를 줄일 수 있음

But there is a widely known convention that properties starting with an underscore "_" are internal and should not be touched from outside the object.

- Static Methods

you can call it directly from the class, but not from an instance of the class.

class School {
  constructor (name, level, numberOfStudents) {
  this._name = name,
  this._level = level,
  this._numberOfStudents = numberOfStudents} // 내가 변수를 넣었을 때 프로퍼티로 불러올 수 있도록
  get name () {
    return this._name  }
  get level () {
    return this._level }
  get numberOfStudents () {
    return this._numberOfStudents } // parameter가 아닌 property 를 얻기 위함 


class Middle extends School { constructor (name, numberOfStudents) {
  super(name, 'middle', numberOfStudents), // level 은 super로 불러오지만 모든 middle이 동일하므로 하나의 string을 넣어준다. 
  this._level=‘Middle' } }
profile
이사간 블로그: yenilee.github.io

0개의 댓글