내부 슬롯과 내부 메서드는 자바스크립트 엔진의 구현 알고리즘을 설명하기 위해 ECMAScript 사양에서 사용하는 의사 프로퍼티와 의사 메서드다. ([[...]])로 감싼 형태.
모든 객체는 [[Prototype]]이라는 내부 슬롯을 갖는데, 내부 슬롯은 자바스크립트 엔진의 내부 로직이므로 직접 접근할 수 없다. 하지만 [[Prototype]] 내부슬롯의 경우, __proto__를 통해 접근 가능하다.
const o = {};
console.log(o);
// {}
// [[Prototype]]: Object
o.__proto__
// {constructor: ƒ, __defineGetter__: ƒ, .... …} // Object.prototype
function test(){}
console.dir(test)
//
ƒ test()
arguments: null
caller: null
length: 0
name: "test"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM2628:1
[[Prototype]]: ƒ () // 모든 객체는 [[Prototype]]이라는 내부 슬롯을 갖는다.
[[Scopes]]: Scopes[1]
자바스크립트 엔진은 프로퍼티
를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트
를 기본값으로 자동 정의한다. 프로퍼티 어트리뷰트는 내부 슬롯 [[Value]] [[Writable]] [[Enumerable]] [[Configurable]]이다. 따라서 프로퍼티 어트리뷰트에 직접 접근할 수는 없지만, Object.getOwnPropertyDescriptor 메서드를 통해 간접적으로 확인 가능하다.
getOwnPropertyDescriptor
const myObj = {};
myObj.name = "kim";
myObj.sayHello = function(){console.log("Hello")}
myObj;
/* {name: 'kim', sayHello: ƒ}
name: "kim"
sayHello: ƒ ()
[[Prototype]]: Object
*/
// 프로퍼티 어트리뷰트 정보를 제공하는 **프로퍼티 디스크립터 객체** 를 반환.
// 프로퍼티 디스크립터 객체는 프로퍼티 어트리뷰트에 해당하는 프로퍼티를 가지고있다.
Object.getOwnPropertyDescriptor(myObj, 'name');
/* {value: 'kim', writable: true,
enumerable: true, configurable: true}
*/
Object.getOwnPropertyDescriptor(myObj, 'sayHello');
// {writable: true, enumerable: true, configurable: true, value: ƒ}
접근자 함수
로 구성된 프로퍼티const person = {
firstName: 'Bumi',
lastName: 'Kim',
get fullName(){
return `${this.firstName} ${this.lastName}`;
},
set fullName(name){
[this.firstName, this.lastName] = name.split(' ');
}
};
// 씬택스 주의
// 접근자 프로퍼티로 setter 함수 호출
person.fullName = "Bumi Lee";
// 접근자 프로퍼티를 통해 getter 함수 호출
console.log(person.fullName);
// Bumi Lee
Object.getOwnPropertyDescriptors(person);
/* firstName: {value: 'Bumi', writable: true,
enumerable: true, configurable: true}
fullName: {enumerable: true, configurable: true,
get: ƒ, set: ƒ}
lastName: {value: 'Lee', writable: true,
enumerable: true, configurable: true}
[[Prototype]]: Object
*/
const o = {};
o.__proto__ ;
/* {constructor: ƒ, __defineGetter__: ƒ,
__defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
*/
Object.getOwnPropertyDescriptor(Object.prototype, '__proto__')
// {enumerable: false, configurable: true, get: ƒ, set: ƒ}
Object.getOwnPropertyDescriptor(o,'__proto__');
// undefined
객체는 객체 리터럴 이외에도 다양한 방법으로 생성할 수 있다.
생성자 함수를 사용하여 객체를 생성하는 방법과 객체 리터럴을 사용하여 객체를 생성하는 방식의 장단점을 살펴본다.
const person = new Object();
// undefined (완료값)
console.log(person)
// {}
// undefined (완료값)
person.name = 'bumi'
// 'bumi'
person.sayHi = function(){console.log('hi')}
// ƒ (){console.log('hi')}
console.log(person)
// {name: 'bumi', sayHi: ƒ}
person.sayHi()
// hi
// undefined (완료값)
생성자 함수란 new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다. 생성자 함수에 의해 생성된 객체를 인스턴스라 한다.
자바스크립트는 Object 생성자 함수 이외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise 등의 빌트인 생성자 함수를 제공한다.
new 연산자와 생성자 함수
객체 리터럴 {...} 을 사용하면 객체를 쉽게 만들 수 있다. 그런데 개발을 하다 보면 유사한 객체를 여러 개 만들어야 할 때가 생기곤 하는데, 복수의 사용자, 메뉴 내 다양한 아이템을 객체로 표현하려고 하는 경우가 그렇다.
=>
'new' 연산자와 생성자 함수를 사용하면 유사한 객체 여러 개를 쉽게 만들 수 있다.
function Circle(radius) {
this.radius = radius;
this.getCircumference = function(){
return this.radius * 2 * Math.PI;
}
this.getArcLength = function(arcAngle){
return this.getCircumference() * arcAngle/360;
}
};
// undefined
// 인스턴스 생성
const circle1 = new Circle(5); // 반지름이 5인 Circle 객체 생성
// undefined
console.log(typeof circle1, circle1);
// object Circle
/* {radius: 5, getCircumference: ƒ, getArcLength: ƒ}
getArcLength: ƒ (arcAngle)getCircumference: ƒ ()
radius: 5
[[Prototype]]: Object
*/
// undefined
circle1.getCircumference();
// 31.41592653589793
circle1.getArcLength(75);
//6.544984694978735
생성자 함수는 말그대로 객체(인스턴스)를 생성하는 함수다. 생성자 함수(constructor function)와 일반 함수에 기술적인 차이는 없다. 다만 생성자 함수는 아래 두 관례를 따른다.
1. 함수 이름의 첫 글자는 대문자로 시작합니다.
2. 반드시 'new' 연산자를 붙여 실행합니다.
3. 생성자 함수 내부에서 return 문을 반드시 생략한다.
인스턴스 생성과 this 바인딩
함수 몸체의 코드가 한 줄씩 실행되는 런타임 이전
에, 생성자 함수가 생성한 인스턴스인 빈 객체가 암묵적으로 생성된다. 그 빈 객체는 this에 바인딩 된다.
function Circle(radius){
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩 된다.
console.log(this); // Circle {}
인스턴스 초기화
생성자 함수에 기술되어 있는 코드가 한 줄씩 실행되어 this에 바인딩 되어있는 인스턴스를 초기화한다. 즉, this에 바인딩 되어 있는 인스턴스에 프로퍼티나 메서드를 추가하고 생성자 함수가 인수로 전달받은 초기값을 인스턴스 프로퍼티에 할당하여 초기화하거나 고정값을 할당한다.
function Circle(radius){
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩 된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function(){
return 2 * this.radius;
};
}
인스턴스 반환
생성자 함수 내부의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
function Circle(radius){
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩 된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function(){
return 2 * this.radius;
};
// 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
}
// 인스턴스 생성 Circle 생성자 함수는 암묵적으로 this를 반환함.
const circle = new Circle(1);
console.log(circle); // Circle {radius: 1, getDiameter: ƒ}
함수는 객체이므로 일반 객체가 가지고 있는 내부 슬로과 내부 메서드를 모두 가지고 있다. 하지만 함수로서 동작하기 위해 함수 객체만을 위한 내부 슬롯과 내부 메서드를 추가로 가지고 있다. 함수가 일반 함수로서 호출되면 함수 객체의 내부 메서드 [[Call]]이 호출되고, new 연산자와 함께 생성자 함수로서 호출되면 내부 메서드 [[Construct]]가 호출된다.
모든 함수는 호출할 수 있기에 내부 메서드 [[Call]]을 가지고 있지만, 모든 함수 객체를 생성자 함수로서 호출할 수 있는 것은 아니다. (= 모든 함수 객체가 [[Construct]]를 갖는 것은 아니다.
자바스크립트 엔진은 함수 정의를 평가하여 함수 객체를 생성할 때 함수 정의 방식에 따라 함수를 constructor와 non-constructor로 구분한다.
// 일반 함수 정의: 함수 선언문, 함수 표현식
function foo(){}
const bar = function () {};
// 프로퍼티 x의 값으로 할당된 것은 일반 함수로 정의된 함수다.
// 이는 메서드로 인정하지 않는다.
const baz = {
x: function () {}
};
new foo();
// foo {}
new bar();
// bar {}
new baz.x();
// x {}
// 화살표 함수 정의
const arrow();
const arrow = () => {};
new arrow();
// Uncaught TypeError: arrow is not a constructor
// 메서드 정의: ES6의 메서드 축약 표현만 메서드로 인정한다.
const obj = {
x() {}
};
new obj.x();
// Uncaught TypeError: obj.x is not a constructor
생성자 함수로서 호출될 것을 기대하지 않고 정의한 일반 함수에 new 연산자를 붙여 호출하면 [[Construct]]가 호출되며 생성자 함수처럼 동작할 수 있다. vice versa, new 연산자 없이 생성한 함수를 호출하면 일반 함수로 호출된다. 즉 [[Call]]이 호출 된다.
// 생성자 함수로서 정의하지 않은 일반 함수
function createUser(name, role){
return {name,role}; // 객체를 반환했기 때문에 new 연산자와 함께 호출했을 때 반환된다.
}
const instance = new createUser('bumi','designer');
instance
// {name: 'bumi', role: 'designer'}
// 생성자 함수
function Circle(radius){
this.radius = radius;
}
// new 연산자 없이 함수를 호출 하여 일반 함수로 호출 됨.
const circle = Circle(1);
circle
// undefined => return문이 없기때문에 자동으로 undefined이 할당됨.
typeof circle
// 'undefined'
여기서 Circle 함수를 new 연산자와 함께 생성자 함수로서 호출하면 함수 내부의 this는 Circle 생성자 함수가 생성할 인스턴스를 가르키지만, Circle 함수를 일반 함수로서 호출하면 함수 내부의 this는 전역 객체 window를 가르킨다.
circle.radius
// Uncaught TypeError: Cannot read properties of undefined
window.radius
// 1
일급 객체의 조건
함수는 위의 조건을 모두 만족하므로 일급 객체이다.
함수는 객체이지만 일반 객체와는 차이가 있다. 함수 객체는 호출 가능하며, 일반 객체에는 없는 함수 고유의 프로퍼티
를 소유한다.
function square(num){
return num * num;
}
console.dir(square)
/*
ƒ square(num)
arguments: null
caller: null
length: 1
name: "square"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM15887:1
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[1]
*/
square 함수의 모든 프로퍼티의 프로퍼티 어트리뷰트를 Object.getOwnPropertyDescriptors 메서드로 확인 해보자.
Object.getOwnPropertyDescriptors(square)
/*
arguments: {value: null, writable: false, enumerable: false, configurable: false}
caller: {value: null, writable: false, enumerable: false, configurable: false}
length: {value: 1, writable: false, enumerable: false, configurable: true}
name: {value: 'square', writable: false, enumerable: false, configurable: true}
prototype: {value: {…}, writable: true, enumerable: false, configurable: false}
[[Prototype]]: Object
*/
// __proto__는 square 함수의 프로퍼티가 아니다!
Object.getOwnPropertyDescriptor(square, '__proto__')
// undefined
// __proto__는 Object.prototype 객체의 접근자 프로퍼티이다.
// square 함수는 Object.prototype 객체로부터 __proto__접근자 프로퍼티를 상속 받는다.
Object.getOwnPropertyDescriptor(Object.prototype, '__proto__');
// {enumerable: false, configurable: true, get: ƒ, set: ƒ}
arguments, caller, length, name, prototype 프로퍼티는 함수 객체 고유의 프로퍼티이다. 하지만 __proto__는 접근자 프로퍼티이며, 함수 객체 고유의 프로퍼티가 아니라 Object.prototype 객체의 프로퍼티를 상속 받는것이다. 즉 모든 객체가 __proto__ 접근자 프로퍼티를 상속받아 사용 가능하다.
function sum(){
let result = 0;
//arguments 객체는 length 프로퍼티가 있는 유사 배열 객체이다.
for(let i = 0; i < arguments.length; i++)
{
result += arguments[i]
}
return result;
}
//
console.log(sum(1,2,3,4,10)); // 20
함수 이름
을 나타낸다. 익명 함수의 경우 ES5에서는 name 프로퍼티는 빈 문자열을 값으로 가지며, ES6에서는 함수 객체를 가리키는 변수 이름
을 값으로 갖는다.function constructor(){}
const nonConstructor = () => {}
constructor.hasOwnProperty('prototype');
// true
nonConstructor.hasOwnProperty('prototype');
// false