자바스크립트 - 객체 2

정영찬·2022년 2월 6일
0

자바스크립트

목록 보기
12/21

프로토타입을 이용한 객체 확장

function Person() {}

Person.prototype.hello = function () {
    console.log('hello');
}


function Korean(region) {
    this.region = region;
    this.where = function () {
        console.log('where', this.region);
    }
}


Korean.prototype = Person.prototype; // Person의 prototype 을 korean에게 전달


const k = new Korean('Seoul');

k.hello(); // Korean 생성자함수로 선언된 객체이지만 Person의 hello메서드를 사용할 수 있다.
k.where();

console.log(k instanceof Korean); // k는 Korean 의 인스턴스인가
console.log(k instanceof Person); // k는 Person 의 인스턴스인가
console.log(k instanceof Object); // k는 Object 의 인스턴스인가.

객체 리터럴

// 객체 리터럴 : 문자그대로 사용한 값이 객체로 만들어지는 기능
const a = {}

console.log(a, typeof a)


const b = {
    name: 'mark'
};

console.log(b, typeof b)



const c = {
    name: "mark",
    hello1() {
        console.log('hello1', this);
    },
    hello2: function () {
        console.log('hello2', this);
    },
    hello3: () => {
        console.log('hello3', this);
    }
};

c.hello1()
c.hello2()
c.hello3()

표준 내장 객체

// 표준 내장 객체: Array


const a = new Array('red', 'black', 'white');
console.log(a, typeof a)
console.log(a instanceof Array)
console.log(a instanceof Object)


const b = ['red', 'green', 'yellow'];

console.log(b, typeof b);
console.log(b instanceof Array);
console.log(b instanceof Object);

//b가 Array의 객체이므로 Array 프로토타입에 속한 함수도 사용이 가능하다.

console.log(b.slice(0, 1));
console.log(Array.prototype.slice, Object.prototype.slice);
//Object.protytpe 에는 slice 함수가 없으나. Array 에서 프로토타입을 받아와서 사용한 것이다.
//그래서 Object.prototype.slice 값이 undefined가 나온다.

profile
개발자 꿈나무

0개의 댓글

관련 채용 정보