스코프(scope)
변수에 접근할 수 있는 범위
전역 스코프 , 지역 스코프< script> let person={ name:'kim', age:30, height:161.1, arr:[1,2,3], toString: function(){ return this.name + "," + this.age + "," +this.height; } } person.name='han'; document.write(person); alert(person); alert(person.toString()); alert(person.name); < /script>
.focus() 여기에 데이터를 입력할 준비를 하라는 의미
객체 생성 방식
1) 객체 리터럴, 2) 생성자 함수, 3) Object.create()1. 객체 리터럴 방식(Object Literal)
var obj = { key: value, ... } : 변수처럼 객체를 생성하는 방식으로, 중괄호 { } 안에 key:value를 쉼표(,)로 구분하여 만든다.
var myObj = {
name: '카레유',
age: 20,
hello: function(){
return이름은 ${this.name}이고, 나이는 ${this.age}입니다.
;
}
};
console.log(myObj);
- myObj 객체가 생성되었다. name, age는 '프로퍼티'이며, hello는 '메서드'다.
키값은 문자열(string)로 작성해야 한다.2. 생성자 방식(Constructor)
: new Constructor() 방식으로 객체를 생성하는 방식이다.
1) new Object() : new 연산자를 통해 Object객체의 생성자함수를 호출한다.
var myObj = new Object();
myObj.name = '카레유';
myObj['age'] = 20;
myObj.hello = function(){
return이름은 ${this.name}이고, 나이는 ${this.age}입니다.
;
};
console.log(myObj);
// { name: '카레유', age: 20, hello: [Function] }
2) new 생성자() : Number, String, Array 등의 내장 객체도 생성할 수 있다.
// String객체 생성하기
var strObj = new String('hello');
console.log(strObj); //[String: 'hello']
// Array(배열)객체 생성하기
var arrObj = new Array([1, 2, 3]);
console.log(arrObj); //[ [ 1, 2, 3 ] ]
3) new 사용자 정의 생성자() : 직접 생성자 함수를 만들어 객체를 생성할 수 있다.
// 생성자 함수 만들기
var SelfObj = function(name, age){
this.name = name; // this는 자신이 속한 객체를 참조하는 '자기 참조 변수'다.
this.age = age;
this.hello = function(){
return이름은 ${this.name}이고, 나이는 ${this.age}입니다.
;
}
}
// 객체 생성하기
var selfObj = new SelfObj('카레유', 20);
console.log(selfObj);
// SelfObj { name: '카레유', age: 20, hello: [Function] }3. Object.create() 방식
Object.create(프로토타입) : 프로토타입 상속을 통해 객체를 만드는 방식이다.
// 부모 객체 생성
var parent = {a:10, b:20};
// 자식 객체 생성(부모의 프로퍼티를 상속 받음)
var child = Object.create(parent);
console.log(child.a); // 10
Hello World!
;}const entries = ["bob", "sally", , , , , , , , "cindy"];
entries.flat(); // 결과 ['bob', 'sally', 'cindy']; r
const userProfiles = [
["commanderTom", 23],
["derekZlane", 20],
];
// 배열을 오브젝트로 변환
const obj = Object.fromEntries(userProfiles);
console.log(obj); // 결과 => [{commanderTom, 23}, {derekZlane, 20}]
// 오브젝트를 배열로 변환
console.log(obj.entries(obj)); // 결과 => [["commanderTom", 23], [derekZlane, 20]]
>**객체 접근 방식**
객체.key, 객체['key'] 방식으로 접근한다. 메서드(함수)는 마지막에 괄호()를 붙여 호출해야 한다.
##### 1) 객체.key : 마침표(Dot Notation)로 프로퍼티에 접근한다.
var myObj = {
name: '카레유',
age: 20,
hello: function(){
return `이름은 ${this.name}이고, 나이는 ${this.age}입니다.`;
}
};
myObj.name; // '카레유'
myObj.age; // 20
myObj.hello(); // '이름은 카레유이고, 나이는 20입니다.'
// key는 객체의 프로퍼티만 허용되기 때문에, 다른 변수를 통해 key값을 참조할 수 없다.(객체['key']방식은 가능)
##### 2) 객체['key'] : 대괄호[ ] 사이에 키값을 '문자열'로 넣어 접근한다.
myObj['name']; // '카레유'
myObj['age']; // 20
myObj['hello'](); // '이름은 카레유이고, 나이는 20입니다.'
// 객체[key] 방식은 key가 따옴표로 감싸져 있지 않으면 변수로 해석해서 참조한다.(객체.key방식은 불가)
myObj[key_age]; // 20
>**메서드 동적 생성**
##### 1. 객체.신규key = 값 or 메서드 : 마침표(dot notation)를 이용해 신규 프로퍼티를 만들 수 있다.
//myObj 객체 생성
var myObj = {
prop_01: 1,
method_01: function(){return 'func_01';}
};
//prop_02 프로퍼티, method_02 메서드 생성
myObj.prop_02 = 2;
myObj.method_02 = function(){return 'func_02'};
//생성 확인
console.log(myObj);
/*
{ prop_01: 1,
method_01: [Function: method_01],
prop_02: 2,
method_02: [Function] }
*/
* prop_02 프로퍼티, method_02 메서드가 추가되었다
##### 2. 객체['신규key'] = 값 or 메서드 : 대괄호[] 안에는 반드시 '문자열' 값을 넣어여 한다.
//prop_03프로퍼티, method_03메서드 생성
myObj['prop_03'] = 3;
myObj['method_03'] = function(){return 'func_03'};
//생성 확인
console.log(myObj);
/*
{ prop_01: 1,
method_01: [Function: method_01],
prop_02: 2,
method_02: [Function],
prop_03: 3,
method_03: [Function] }
*/
* prop_03 프로퍼티, method_03 메서드가 추가되었다
>**메서드 삭제**
delete 연산자를 사용하면, 객체의 프로퍼티나 메서드를 제거할 수 있다.
##### 1. delete 객체.key : 도트(.) 접근법을 이용해 프로퍼티를 삭제한다.
//prop_03, method_03 삭제
delete myObj.prop_03;
delete myObj.method_03;
//삭제 확인
console.log(myObj);
/*
{ prop_01: 1,
method_01: [Function: method_01],
prop_02: 2,
method_02: [Function] }
*/
* prop_03 프로퍼티, method_03 메서드가 삭제되었다.
##### 2. delete 객체['key'] : [] 접근법를 이용해 프로퍼티를 삭제한다.
//prop_02, method_02 삭제
delete myObj['prop_02'];
delete myObj['method_02'];
//삭제 확인
console.log(myObj);
* prop_02 프로퍼티, method_02 메서드가 삭제되었다.
- 프로퍼티 key에 계산식 사용
객체 내부에서 프로퍼티의 key를 [계산식] 로 사용할 수 있다.
var num_01 = 1;
var num_02 = 2;
var strHello = 'hello';
var newObj = {
[1 + 1]: 'first',
[num_01 + num_02]: 'second',
[strHello + num_01]: num_02,
[`${strHello} - ${num_01 + num_02}`]: 'fourth'
};
console.log(newObj);
//{ '2': 'first', '3': 'second', hello1: 2, 'hello - 3': 'fourth' }
- spread 연산자
...을 통해 사용할 수 있다
전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있다
ex)
const arr = [1, 2, 3, 4, 5];
console.log(arr); // [ 1, 2, 3, 4, 5 ]
console.log(...arr); // 1, 2, 3, 4, 5
console.log(1, 2, 3, 4, 5); // 1, 2, 3, 4, 5
ex)
const aArr = [1, 2, 3];
const bArr = [4, 5, 6];
// array.concat
console.log(aArr.concat(bArr)); // [ 1, 2, 3, 4, 5, 6 ]
// spread
console.log([...aArr, ...bArr]); // [ 1, 2, 3, 4, 5, 6 ]
>#### 함수에서 객체를 파라미터로 받기
```js
const ironMan = {
name: '토니 스타크',
actor: '로버트 다우니 주니어',
alias: '아이언맨'
};
const captainAmerica = {
name: '스티븐 로저스',
actor: '크리스 에반스',
alias: '캡틴 아메리카'
};
//원조
function print(hero) {
const text = `${hero.alias}(${hero.name}) 역할을 맡은 배우는 ${
hero.actor
} 입니다.`;
console.log(text);
}
//비구조화 할당
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);
}
출력
아이언맨(토니 스타크) 역할을 맡은 배우는 로버트 다우니 주니어 입니다.
캡틴 아메리카(스티븐 로저스) 역할을 맡은 배우는 크리스 에반스 입니다.
객체 안에 함수 넣기
const dog = { name: '멍멍이', sound: '멍멍!', say: function say() { console.log(this.sound); } }; dog.say(); 출력 멍멍!
객체 안에서 함수를 넣을때 화살표 함수로 선언은 불가하다
: function으로 선언한 함수는 this 가 제대로 자신이 속한 객체를 가르키게 되는데,
화살표 함수는 그렇지 않음
Object.key(객체명).length
Object.value(객체명).length
__proto__
를 가지고 있다__proto__
는 프로토타입 링크라 하는데 객체 생성시 사용한 생성자의 prototype object를 가르킨다const featureNewArray = Object.keys(list).map((ele, i) => {
const newArr = []
const title = findTitle(ele, data)
const value = Object.values(list).map(v => v)
newArr.push({
title: title[i],
count: value[i],
})
return newArr
})
//결과값
[{title: 'a', count: 2},
{title:'b', count:1}]