Object 생성자 함수

 

new 연산자와 함께 Object 생성자 함수를 호출하면 빈 객체를 생성하여 반환한다. 빈 객체를 생성한 이후 프로퍼티 또는 메서드를 추가하여 객체를 완성할 수 있다.

 

const person = new Object();    //빈 객체 생성

person.name = "kiwon";
person.sayHello = function(){
    console.log(`hello my name is ${this.name}`);
};
console.log(person);
person.sayHello();

 

 

생성자 함수란 new연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수이다.

생성자 함수에 의해 생성된 객체를 인스턴스라 한다.

생성자는 String, Number, Boolean, Function 등등 여러가지가 있다.

 

const strObj = new String("hello");
console.log(strObj); //String ("hello")
console.log(typeof strObj); //object
const arr = new Array(1,2,3);
console.log(arr); // 1,2,3
console.log(typeof arr) //object

 

반드시 생성자 함수를 사용해 빈객체를 생성해야 하는 것은 아니다. 객체를 생성하는 방법은 객체 리터럴을 사용하는 것이 더 간편하다.

 


this

 

this는 객체 자신의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수다.

this가 가리키는 값은 함수 호출 방식에 따라 동적으로 결정된다.

 

  • 일반 함수로서 호출 : 전역 객체
  • 메서드로서 호출 : 메서드를 호출한 객체
  • 생성자 함수로서 호출 : 생성자 함수가 생성할 인스턴스

 

function foo(){
    console.log(this); // node.js
}

//전역 객체는 브라우저환경에서는 window, node.js에서는 global을 가리킨다.

foo();

const obj = {foo};
obj.foo(); //obj

const inst = new foo(); //inst

 

 

'WEB > JS' 카테고리의 다른 글

[JS] 프로토타입  (1) 2023.12.02
[JS] constructor, non-constructor  (0) 2023.11.28
[JS] 프로퍼티 어트리뷰트  (0) 2023.11.27
[JS] let, const키워드와 블록 레벨 스코프  (1) 2023.11.27
[JS] scope(유효범위)  (0) 2023.11.25

+ Recent posts