const person = new Object({name: 'Lee'});
console.log(person);
const strObj = new String('str');
console.log(typeof strObj); // object
console.log(strObj); // __proto__는 String
const whatType = new Object('str'); // String로 생성안해도 js가 알아서 prototype을 잘 지정해주긴 한다
console.log(typeof whatType); // 타입은 object
console.log(whatType); // __proto__는 String
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를 안쓰면 Circle은 일반 함수로써 동작한다
const circle3 = Circle(15);
console.log(circle3); // undefined
console.log(radius); // 15, Circle이 전역 객체로 생성됐다. this가 window이기 때문
// 멤버로 추가해 메서드로써 호출할 경우
const circle4 = { Circle }; // Circle의 this는 circle4를 가리킨다
circle4.Circle(20);
console.log(circle4);
| 함수 호출 방식 | this가 가리키는 값(this 바인딩) |
|---|---|
| 일반 함수로서 호출 | 전역 객체 |
| 메서드로서 호출 | 메서드를 호출한 객체(마침표 앞의 객체) |
| 생성자 함수로서 호출 | 생성자 함수가 (미래에) 생성할 인스턴스 |
function Circle(radius) {
// 1. 암묵적으로 빈 객체가 생성되어 this에 바인딩
// 2. this에 바인딩되어 있는 인스턴스를 초기화
this.radius = radius;
this.getDiameter = function() {
return 2 * this.radius;
};
// 3. ★return은 생략★ 완성된 인스턴스(가 바인딩된 this)가 암묵적으로 반환된다.
// return {}; // 명시적으로 객체를 반환한다면, {}가 리턴된다
// return 10; // 명시적으로 원시값을 리턴하면, 이 return은 무시된다
}
const circle = new Circle(5);
console.log(circle); // Circle {radius: 5, getDiameter: f}
function foo() {}
foo(); // [[Call]] 호출
new foo(); // [[Construct]] 호출
function foo1() {}
new foo1();
const foo2 = function () {};
new foo2();
const foo3 = {
x: function () {} // 메서드가 아니고 일반함수다
};
new foo3.x();
const foo1 = () => {};
new foo1(); // TypeError: foo1 is not a constructor
const foo2 = {
x() {} // 메서드 정의
};
new foo2.x(); // TypeError: foo2.x is not a constructor
function add(x,y) {
return x + y;
}
const obj = new add();
console.log(obj); // add{}, add라는 이름의 빈 객체를 생성
모든 생성자 함수의 이름은 첫글자를 대문자로! 🙏
function Circle(radius) {
if(!new.target) { // new로 호출되지 않았다면, new.target = undefined 이다
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function() {return 2 * this.radius;}
}
const circle = Circle(5);
console.log(circle.getDiameter()); // 10
// 만약 일반함수 였다면, TypeError: Cannot read properties of undefined (reading 'getDiameter')가 발생했을 것
function Circle(radius) {
console.log(this instanceof Circle); // false
if(!(this instanceof Circle)) { // new로 호출되지 않았다면, this는 Window이다
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function() {return 2 * this.radius;}
}
const circle = Circle(5);
console.log(circle.getDiameter()); // 10