TIL0508 배열과 객체,this,prototype

Yunji·2020년 5월 10일
0

TIL

목록 보기
45/54

javascript

배열과 객체

배열은 저장된 데이터들이 순서를 가지고 있어 인덱스로 접근 가능하다

arr[1];

배열은 .length 로 반복문을 돌릴 수 있다
객체는 key 와 value 로 구성되어 있고 순서가 없다
그렇기 때문에 객체에서 반복문을 쓰려면 for(let 객체의키 in 객체) 을 사용하면 된다

const arr1 = {
	name: 'pin',
  	age: 25,
  	hobby: 'movie'
}
for(let key in arr1) {
	console.log(arr1[key]);
}
//'pin', 25, 'movie'출력

객체의 사용

Math 라는 객체는 안에 PI, random(),floor 등 변수, 함수들이 그룹되어 있는 것이다

console.log("Math.PI",Math.PI);   // 'Math.PI' 3.141592653589793
console.log("Math.random()",Math.random());   // 'Math.random()' 0.2464938786627353
console.log("Math.floor(3.9)",Math.floor(3.9));   // 'Math.floor(3.9)' 3

자바스크립트는 객체지향 언어이다 이미 만들어진 객체를 사용하지 않고 애플리케이션을 만든다는 것은 사실상 불가능하다
Math 객체를 만들어보면

const MyMath = {
  PI: Math.PI,
  random: function() {
    return Math.random();
  },
  floor: function(val) {
    return Math.floor(val);
  }
}

객체는 서로 연관된 변수와 함수들을 그룹해서 이름을 붙인 것이다
객체 안에는 함수도 저장 될 수 있다 객체 안에 있는 함수를 매서드라고 한다

this

this는 대명사와 같은 느낌이다 this 는 약속되어 있는 변수로 자신이 속해있는 객체를 가리킨다
화살표 함수의 this 는 언제나 상위 스코프를 가리킨다 그래서 메소드를 정의할 때는 화살표 함수를 쓰지 않는 것이 좋다 대신 ES6의 축약 메소드 표현을 사용하는 것이 좋다

const kim = {
  name: 'kim',
  firstGame: 10,
  secondGame: 20,
  sum: function() {
    return this.firstGame + this.secondGame;
  }
}
=>
const kim = {
  name: 'kim',
  firstGame: 10,
  secondGame: 20,
  sum() {
    return this.firstGame + this.secondGame;
  }
}

addEventListener 에서도 콜백함수로 화살표 함수를 쓰면 this 가 전역 객체를 가리키기 때문에 사용하지 않는 것이 좋다

construct function 을 사용하면 동일한 구조의 객체가 필요할 때 마다 만드는 수고를 덜 수 있다
새로운 객체가 필요할 때 마다 미리 정의해둔 함수에 new를 붙이고 값만 변경해서 호출하면 된다

function Person(name, first, second, third) {
  this.name = name;
  this.first = first;
  this.second = second;
  this.third = third;
  this.sum = function(){
    return this.firstGame + this.secondGame;
  }
}
console.log("new Person()", new Person('kim', 10, 20, 50));
//
'new Person()' Person {
  name: 'kim',
  first: 10,
  second: 20,
  third: 50,
  sum: [Function]
}

prototype

prototype based language
자바스크립트는 클래스의 개념이 없는 대신 prototype 이 존재한다 그래서 자바스크립트를 프로토타입 기반 언어라고도 부른다
자바스크립트의 모든 객체는 객체 원형에 대한 연결을 가지고 있다
생성자 안에서 메소드를 만들면 수정이 힘들어 생산성이 떨어진다 그래서 prototype 을 쓴다
prototype 을 쓰면 새로운 객체가 만들어질 때 마다 메소드가 실행되지 않고 공유되는 함수만 실행되기 때문에 더 효율적이다 코드의 수정도 쉽게 가능하다

function Person(name, first, second, third) {
  this.name = name;
  this.first = first;
  this.second = second;
}
Person.prototype.sum = function(){
    return 'prototype : ' + this.first + this.second;
}
let kim = new Person('kim', 10, 20);
// 또 특정 객체의 메소드를 따로 설정할 수도 있다
kim.sum = function(){
    return 'this : ' + this.first + this.second;
}
let lee = new Person('lee', 30, 20);
console.log("kim.sum()",kim.sum());
console.log("lee.sum()",lee.sum());

0개의 댓글