Built in Constructor 본문

2021 프론트 엔드 로드맵 따라가기/JS

Built in Constructor

알 수 없는 사용자 2021. 6. 5. 10:48

JS에 기본적으로 내장되어 있는 생성자들을 이야기한다.

primitive type의 데이터들은 해당 생성자로 생성할 경우 object로 생성됨에 주의하고, 정규표현식 같은 경우에는 생성자를 이용할 때 escaping을 해줘야 한다는 점에 주의하도록 하자.

 

또한, 해당 생성자들을 이용할 경우 시간이 더 오래 걸린다고 한다.

// String
const name1 = "jian";
const name2 = new String("jian");

// name2.foo = "bar";
console.log(name2);

console.log(typeof name1);  // String
console.log(typeof name2);  // Object

if (name2 === "jian") { // No, because name2 is an object
  console.log("Yes");
} else {
  console.log("No");
}

// Number
const num1 = 5;
const num2 = new Number(5);

console.log(typeof num2);

// Boolean
const bool1 = true;
const bool2 = new Boolean(true);

console.log(typeof bool2);

// Function
const getSum1 = function (x, y) {
  return x + y;
};

const getSum2 = new Function("x", "y", "return x + y");

console.log(getSum2(1, 1));

// Object
const john1 = {name: "John"};
const john2 = new Object({name: "John"});

console.log(john1);

// Array
const arr1 = [1, 2, 3, 4];
const arr2 = new Array(1, 2, 3, 4);

console.log(arr2);

// Regular Expreesions
const re1 = /\w+/;
const re2 = new RegExp("\\w+");  // need escape

console.log(re2);

'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글

[중요] Prototypal inheritance  (0) 2021.06.05
Prototype  (0) 2021.06.05
Hoisting  (0) 2021.06.05
특정 범위의 랜덤 정수 값 생성 코드  (0) 2021.06.04
Number()와 parseInt() 차이  (0) 2021.06.04
Comments