자바스크립트 생성자 함수에 의한 객체 생성

csb·2021년 1월 17일
0

자바스크립트

목록 보기
5/7

Object 생성자 함수

new 키워드를 사용하여 생성하는 함수를 의미

const person = new Object();

person.name = 'Lee';
person.sayHello = function () {
	console.log('Hi! My name is ' + this.name);
};

console.log(person); // { name: "Lee", sayHello: f }
person.sayHello(); // Hi! My name is Lee
const strObj = new String('Lee');
console.log(typeof strobj); // object
console.log(strObj); // String { "Lee" }

const numObj = new Number(123);
console.log(typeof numObj); // object
console.log(numObj); // Number { 123 }

const boolObj = new Boolean(true);
console.log(typeof boolObj); // object
console.log(boolObj); // Boolean { true }

const func = new Function('x', 'return x * x');
console.log(typeof func); // function
console.dir(func); // f anonymous(x)

const arr = new Array(1, 2, 3);
console.log(typeof arr); // object
console.log(arr); // [1, 2, 3]

const regExp = new RegExp(/ab+c/i);
console.log(typeof regExp); // object
console.log(regExp); // /ab+c/i

const date = new Date();
console.log(typeof date); // object
console.log(date); // Mon May 04 2020 08:36:33 GMT+0900 (대한민국 표준시)

생성자 함수

반복된 코드를 사용하는 나쁜 사례

const circle1 = {
	radius: 5,
    getDiameter() {
    	return 2 * this.radius;
    }
};

console.log(circle1.getDiameter()); // 10

const circle2 = {
	radius: 10,
    getDiameter() {
    	return 2 * this.radius;
    }
};

console.log(circle2.getDiameter()); // 20

개선된 패턴을 사용하는 좋은 사례

function Circle(radius) {
	this.radius = radius;
    this.getDiameter = function() {
    	return 2 * this.radius;
    }
}

const circle1 = new Circle(5);
const circle2 = new Circle(10);

console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20

new 연산자

new 연산자와 함께 호출하면 해당 함수는 생성자 함수로 동작한다.
new 연산자와 함께 생성자 함수를 호출하지 않으면 생성자 함수가 아니라 일반 함수로 동작한다.

const circle3 = Circle(15);

console.log(circle3); // undefined

console.log(radius); // 15
function add(x, y) {
	return x + y;
}

let inst = new add();

console.log(inst); // {}

function createUser(name, role) {
	return { name, role };
}

inst new createUser('Lee', 'admin');
console.log(inst); // { name: "Lee", role: "admin" }

new.target (IE 지원 X)

생성자 함수가 new 연산자 없이 호출되는 것을 방지하기 위해 파스칼 케이스 컨벤션을 사용한다 하더라도 실수는 발생할 수 있기 때문에 ES6에서는 new.target을 지원한다.

function Circle(radius) {
	if (!new.target) {
    	return new Circle(radius);
    }
    
    this.radius - radius;
    this.getDiameter = function() {
    	return 2 * this.radius;
    }
}

const circle = Circle(5);
console.log(circle.getDiameter()); // 10

String, Number, Boolean 생성자 함수는 new 없이 호출시 각각의 데이터 타입을 반환한다

const str = String(123);
console.log(str, typeof str); // 123 string

const num = Number('123');
console.log(num, typeof num); // 123 number

const bool = Boolean('true');
console.log(bool, typeof bool); // true boolean

참고

0개의 댓글