Javascript5(Object) feat.Ellie&velopert

min seung moon·2021년 3월 4일
0

Javascript

목록 보기
5/23

Object

  • one of the JavaScript's data types.
    • 자바스크립트 타입 중 하나이다
  • a collection of related data and/or functionality
    • 기능과 데이터의 집합
  • Nearly all objects in JS are intances of Object
    • JS의 객체는 거의 모두 Object의 인스턴스이다
  • object = { key : value };
  • 하나의 이름에 여러 값 종류의 값을 넣을 수 있다

1. Literals and properties

  • primity type은 변수 하나당 값을 하나만 담을 수 있다
  • 인자가 많아지면 지저분 해지고 효율적이지 못하다
// 변수에 값 대입하고 출력
function print(name, age) {
	console.log(name);
	console.log(age);
}
const name = 'ellie';
const age = 4;
print(name, age);

// 객체에 값 대입하고 출력
function print(person) {
	console.log(person.name);
	console.log(person.age);
}
const ellie = {name : 'ellie', age : 4};
print(ellie);

1. Object 생성

  • quali bracket, 'object literal' syntax
    const object1 = {};
  • Class new keyword, 'object constructor' syntax
    const obj2 = new Object();

2. dynamic claire type language

  • 동적으로 타입이 runtime 때 결정
  • 뒤늦게 하나의 프로퍼티를 추가할 수 있다
ellie.hasJob = true;
console.log(ellie.hasJob);
  • 삭제도 가능하다
delete ellie.hasJob;
console.log(ellie.hasJob);

2. Computed properties(계산된 properties)

  • object는 .(dot) 과 ['key']를 통해서 value를 갖고 올 수 있다
  • key should be always string, []을 사용할 때는 무조건 string type으로 지정
// 코딩하는 그 순간, 그 키의 해당하는 값을 받아오고 싶을 때
console.log(ellie.name); 

// 우리가 정확히게 어떤키가 필요한지 모를 때, 우리가 실시간으로 값을 받아오고 싶을 때
console.log(ellie['name']); 
ellie['hasJob'] = true;
console.log(ellie.hasJob);

// key 값이 특정되지 않을 경우 .을 사용하면 값을 받아 올 수 없다
// 그럴 때는 computed properties를 사용한다
function printValue(obj, key) {
	// console.log(obj.key);
	console.log(obj[key]);
}
printValue(ellie, 'name'); // ellie

3. property value shorthand

const person1 = { name : 'bob', age : 2};
const person2 = { name : 'steve', age : 3};
const person3 = { name : 'dave', age : 4 };
const person4 = Person('ellie', 30);

// 다른 계산 없이 순수 객체를 생성할 때는 함수명은 대문자로 시작하게 하고
function Person(name, age) {
	// key 와 value의 이름이 같으면 생략할 수 있다
	return {
		name,
		age
	}
}

4. Constructor Function

function Person(name, age) {
	// return 대신에 class에서 object를 만드는 것 처림 this를 사용할 수 있다
	// this = {}; 생략
	this.name = name;
	this.age = age;
	// return this; 생략 가능
}
const person5 = new Person('ellie', 30);

5. in Operator : property existence check (key in obj)

  • 해당하는 obj 안에 key가 있는지 없는지 확인
  • key in object
console.log('name' in ellie); //true
console.log('age' in ellie);  // true
console.log('random' in ellie); // false

6. for..in vs for..of

  • for (key in obj)
for (key in ellie) {
	console.log(key); // obj안에 잇는 key를 출력 not value
}
  • for (value of iterable)
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++){
	console.log(array[i]);
}

for(value of array) {
	console.log(value);
}

7. Fun cloning(복사 함수)

  • Object.assign(dest, [obj1, obj2, obj3...])
const user = { name : 'ellie', age : '20'};
const user2 = user; // user와 동일한 ref가 할당되어 있고 동일한 값을 가리킴
user2.name = 'coder';
console.log(user.name); // coder
        
// old way
const user3 = {};
for (key in user) {
	user3[key] = user[key];
}
console.log(user3);

// new way
Object.assign()
// 복사하고자 하는 타겟과 복사할려고 하는 source를 같이 전달
// return 타겟과 복사하고자 하는 값이 return 된다
const user4 = {};
Object.assign(user4, user);
console.log(user4);

const user4 = Object.assign({}, user);
console.log(user4);

// 여러개의 값
const fruit1 = { color : 'red' };
const fruit2 = { color : 'blue', size : 'big' };
const mixed = Object.assign({}, fruit1, fruit2);
console.log(mixed.color); // 같은 key 값 인경우 뒤에 있는 key 값을 덮어 씌운다

8. destructuring assignment(비구조할당, 구조분해)

  • 객체의 값을 불러올 때 .을 사용하지 않고 내부에 있는 값을 빼서 사용하는 방법
  • 비구조 할당은 함수 뿐만이 아니라 변수에도 사용 가능하다
const ironMan = {
	name : '토니 스타크',
	actor : '로버트 다우니 주니어',
	alias : '아이언 맨'
};
const captainAmerica = {
	name : '스티븐 로저스',
	actor : '크리스 에반스',
	alias : '캡틴 아메리카'
};
function print(hero) {
	const { alias, name, actor } = hero;
	const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor}`;
	console.log(text);
}

// 파라메터에서도 비구조 할당이 가능 하다
function print({ alias, name, actor }) {
	const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor}`;
	console.log(text);
}

9. 객체 안에 함수 넣기

const dog = {
	name : '멍멍이',
	sound : '멍멍',
	say : function () {
		console.log(this.sound);
	}
	say2 : () => {
		// 화살표 함수에서는 this 키워드를 사용할 수 없다
		// function에서의 this는 자기가 속해있는 곳을 가리킴
		// 화살표 함수에서는 자기가 속해있는 곳을 가리키지 못함
		console.log(this.sound);
	}
};
dog.say();

// 객체에 바로 함수 생성
const dog = {
	name : '멍멍이',
	sound : '멍멍',
	say : function () {
		console.log(this.sound);
	}
};

// 객체 생성 후 함수 할당
const cat = {
	name : '야옹이',
	sound : '야용~'
};
cat.say = dog.say;
dog.say();
cat.say();

10. getter, setter 함수

  • getter함수(특정값을 조회할 때 특정 코드 사용), setter(객체 내부의 값을 변경 할 때 사용, 무조건 파라메터(매개변수)가 있어야 한다)
  • 객체안에 property(값)과 getter, setter이름은 같을 수 없으나 getter와 setter끼리는 같아도 된다
// 객체안의 직접 접근
const numbers = {
	a: 1,
	b: 2
};
numbers.a = 5;
// a의 값이 변경 됨
console.log(numbers.a); // 5

// 함수를 이용해서 객체 내부의 인수 계산
const numbers = {
	a: 1,
	b: 2,
	get sum() {
		console.log('sum 함수가 실행됩니다!')
		return this.a + this.b;
	}
};
console.log(numbers.sum);   // 3
numbers.b = 5;
console.log(numbers.sum);   // 6

// setter 사용하여 값 전달
// 실제 값이 전달되는 data의 이름을 바꿔주어야 name stter를 사용 가능
// 만약 바꾸지 않으면 setter 반응 없음
const dog = {
	_name : '멍멍이',
	set name(value) {
		console.log('이름이 바뀝니다..'+value);
		this._name = value;
	}
}
console.log(dog._name); // 멍멍이
dog.name = '뭉뭉이';
console.log(dog._name); // 뭉뭉이

// getter, setter 만들기
// getter, setter는 동일한 이름이어도 된다
const dog = {
	_name : '멍멍이',
	get name() {
		console.log('_name을 조회합니다..');
		return this._name;
	},
	set name(value) {
		console.log('이름이 바뀝니다..'+value);
		this._name = value;
	}
};
console.log(dog._name); // 멍멍이
dog.name = '뭉뭉이';
console.log(dog.name); // 뭉뭉이

const numbers = {
	_a : 1,
	_b : 2,
	sum : 3,
	calulate() {
		console.log('calculate');
		this.sum = this._a + this._b;
	},
	get a() {
		return this._a;
	},
	get b() {
		return this._b;
	},
	set a(value) {
		this._a = value;
		this.calculate();
	},
	set b(value) {
		this._b = value;
		this.calculate();
	}
};
console.log(numbers.sum);
numbers.a = 5;
console.log(numbers.sum);
numbers.b = 7;
console.log(numbers.sum);

11. 객체를 배열로 반환하는 방법

  • Object.entries(객체), Object.keys(객체), Object.values(객체)
  • Obejct.entries(객체)
    • 객체를 배열로 반환
  • Objec.keys(객체)
    • 객체의 키값을 배열로 반환
  • Objec.values(객체)
    • 객체의 키 안에 있는 값을 배열로 반환

12. Prototype

  • 함수를 통해 새로운 객체를 만드는 것
function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound =sound;
	this.say = function () {
		console.log(this.sound);
	}
}
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound =sound;
}
Animal.prototype.say = function() {
	console.log(this.say);
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
  • 객체 상속자 상속
// Dog, Cat 객체생성 함수
function Dog(name, sound) {
	this.type = "개";
	this.name = name;
	this.sound = sound;
}

function Cat(name, sound) {
	this.type ="고양이";
	this.name = name;
	this.sound = sound;
}

Dog.prototype.say = function() {
	console.log(this.sound);
}
Cat.prototype.say = function() {
	console.log(this.sound);
}

function Animal(type, name, sound) {
	this.type = type;
	this.name = name;
	this.sound = sound;
}

// .call을 이용한 객체 생성자 함수상속
Animal.prototype.say = function() {
	console.log(this.sound);
}
// .call(현재객체생성자this, 불러오는 부모의 파라미터에 맞춰서 파라미터 입력)
function Dog(name, sound) {
	Animal.call(this, "개", name, sound);
}

function Cat(name, sound) {
	Animal.call(this, "고양이", name, sound);
}

Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;
profile
아직까지는 코린이!

0개의 댓글