210419_객체(Object)

객체(Object)

mdn
mdn2

현실의 사물을 프로그래밍에 반영한 것

자바스크립트에서 원시 타입을 제외한 모든 데이터 타입(객체, 함수, 배열, 정규표현식 등)은 객체.

객체 생성 방식

object literal

const person = {}; 빈 오브젝트 생성 
person //  {} 
var nara = {
  firstName: 'bitara',
  lastName: 'Lee'
}; // {}로 감싼 덩어리가 나를 표현하는 객체
  • 속성(Property):
    콤마로 구분되는 것들
    속성끼리는 쉼표로 구분
    키:값의 pair로 이루어짐

  • 키(key):
    속성에서 firstName과 lastName
    속성명(property's name)
    문자열이지만 따옴표가 없어도 된다(but 키에 띄어쓰기 들어간 경우 따옴표 필요)
    ex) var sami = { 'Lee sami': 'sister' };

  • 값(value):
    속성에서 'bitnara'와 'Lee'
    다양한 데이터 타입 가짐
    객체가 보유한 함수를 'method'라고 한다

  • object는 length가 없다(return undefined)

ES6 새롭게 추가된 객체 리터럴 기능

Constructor(생성자 방식)

: new Constructor() 방식으로 객체를 생성하는 방식이다.

  • new Object() : new 연산자를 통해 Object객체의 생성자함수를 호출
var myObj = new Object();

myObj.name = 'nara';
myObj['age'] = 15;

myObj.hello = function(){
    return `이름은 ${this.name}이고, 나이는 ${this.age}입니다.`;
};

console.log(myObj);  // { name: 'nara', age: 15, hello: [Function] }
  • 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 ] ]

  • 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('nala', 20);
console.log(selfObj); // SelfObj { name: 'nala', age: 20, hello: [Function] }
 

Object.create()

Object.create(프로토타입) : 프로토타입 상속을 통해 객체를 만드는 방식이다.

  *이 방식은 프로토타입, 상속 등의 개념이 필요한 관계로 여기선 간단한 예만 정리한다.

// 부모 객체 생성
var parent = {a:10, b:20};

// 자식 객체 생성(부모의 프로퍼티를 상속 받음)
var child = Object.create(parent);
console.log(child.a);  // 10
 
* child객체에서 parent객체의 프로퍼티인 a값을 참조할 수 있게 되었다.

One limitation of create() is that IE8 does not support it. So constructors may be more effective if you want to support older browsers.

객체 속성(property) 조회

var nara = { 
      firstName: 'bitnara',
      age: 20,
      hello: function(){
           return `이름은 ${this.name}이고, 나이는 ${this.age}입니다.`; 
      } 
 };

dot notation

nara.firstName;      // 'bitnara'
nara.age;            // 20 
nara.hello();        // '이름은 bitnara이고, 나이는 20입니다.'

bracket notation

nara['firstName'];      // 'bitnara'
nara['age'];            // 20 
nara['hello']();        // '이름은 bitnara이고, 나이는 20입니다.'

  • nara.firstName와 nara['firstName']의 차이: firstName 는 정의되지 않은 변수로 취급
    var key_name = ‘firstName’; ------->>>> ‘firstName’을 key_name에 할당
    nara.key_name; // undefined
    nara[key_name] // ‘firstName’------>>>> 변수 key_name을 nara의 property에 넣어주는 것이 됨.

key값이 변수 일 때 : [] bracket notation 사용해야함 (코플릿1번)
bracket notation : 정확히 어떤 키가 필요한지 모를때(런타임에서 결정될때) - 실시간으로 원하는 키를 받아오고 싶다면
dot notation : 동적인 변수 못 담음, 코딩시 즉각적으로 결과 얻고 싶을때.

Property/Method 동적 생성

자바스크립트는 객체 생성이 완료된 후에도, 프로퍼티나 메서드를 추가 가능

  • 객체.신규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 메서드가 추가되었다
  • 객체['신규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 메서드가 추가되었다

nara[‘hobby’] = ‘drawing’;
nara.tags = [‘#code’ , ‘#coding’]; ----->>>> nara.tags[0] / nara[‘tag’][0]
->array안의 element 한번에 부를수도 있다

Sub-namespaces

making the value of an object member another object.

nara.name[0]
nara.name[1]
nara.name.first
nara.name.last
nara['age']
nara['name']['first']

function  makePerson(name, age) {
  return {
    name : name; //key와 value 값의 이름이 같으면 하나로 생략가능
name: name, ----> name,
    age : age;
  };
}

constructor function
function Person(name, age) {//순수하게 오브젝트 리턴하는 함수들은 대문자로 시작
  this.name = name; //this = {}'
  this.age = age;
}
const person4 = new Person('elie', 30); //호출할때도 new붙임

동적 프로퍼티/메서드 삭제

  • delete 키워드를 사용하면, 객체의 프로퍼티나 메서드를 제거할 수 있다.

delete nara.age;
delete nara['age'];

(others)

for (variable in object)
statement

iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
A different property name is assigned to variable on each iteration
-for (value of iterable) ->순차적으로 배열가능한 것에만-배열등에만 씀

obj.hasOwnProperty(prop):
A Boolean indicating whether or not the object has the specified property as own property.

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

Object.keys()
returns an array of a given object's own enumerable property names

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]

(cloning)

Object.assign()
copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

const nara = { name: 'bitnara', age: '20' };

old way
const user3 = {};
for(key in user) {
  user3[key] = user[key];
  }
  console.log(user3);
---------------------------------  
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

좋은 웹페이지 즐겨찾기