const x = {};
x.name = 'Kim'; // 할당 가능
x = null; // 오류
function greeter(name) {
this.name = name;
}
greeter.prototype.greet1 = function () {
setTimeout(function () {
console.log("hello", this.name); // function 내부에 선언되어 있는 this는 있으나, name이라는 키를 가진 값은 없음
}, 500);
};
greeter.prototype.greet2 = function () {
setTimeout(
function () {
console.log("hello", this.name);
}.bind(this), // 부모(greeter)의 this와 bind
500
);
};
greeter.prototype.greet3 = function () {
setTimeout(() => {
console.log("hello", this.name); // 부모(greeter)의 this에 접근 가능
}, 500);
};
const g = new greeter("world");
g.greet1(); // hello undefined
g.greet2(); // hello world
g.greet3(); // hello world
클래스 구문
다른 객체지향 언어와 거의 유사한 형태로 class, extends contructor, super 사용 가능함
향상된 객체 리터럴
// function 키워드 생략, 별도의 키 이름 생략
module.exports = {
square (x) {
return x * x;
},
cube (x) {
return x * x * x;
}
};
// setter, getter 사용 가능
const person = {
name: "George",
surname: "Boole",
get fullname() {
return `${this.name} ${this.surname}`;
},
set fullname(fullname) {
const [name, surname] = fullname.split(" "); // array destructuring
this.name = name;
this.surname = surname;
},
};
console.log(person.fullname); // George Boole
console.log((person.fullname = "Alan Turing")); // Alan Turing
console.log(person.name); // Alan
const tests = new Map();
tests.set(() => 2 + 2, 4);
tests.set(() => 2 * 2, 4);
tests.set(() => 2 - 2, 1);
for (const [test, result] of tests) { // array destructuring
console.log(test() === result ? "PASS" : "FAIL");
}
Set 또한 함수와 객체를 키로 사용할 수 있으며, 타 언어와 거의 유사한 기능을 가짐.
// Map
let obj1 = { key: "val1" }; // ref count: 1
const map = new Map();
map.set(obj1, "obj1 value"); // obj1의 ref count: 2
console.log(map); // Map(1) { { key: 'val1' } => 'obj1 value' }
obj1 = undefined; // ref count: 1
console.log(map); // Map(1) { { key: 'val1' } => 'obj1 value' }, obj1를 키로 사용하여 접근할 방법은 없지만 Map 내에 객체가 살아 있음
// WeakMap
let obj1 = { key: "val1" }; // ref count: 1
const weakMap = new WeakMap();
weakMap.set(obj1, "obj1 value"); // obj1의 ref count가 올라가지 않음. ref count: 1
console.log(weakMap.has(obj1));
obj1 = undefined; // ref count: 0, 객체 제거됨
console.log(weakMap.has(obj1)); // undefined 를 사용하여 접근 불가. weakMap 내에 객체가 존재하지 않고, 접근할 방법도 없음.