const elf = {
name: 'Orwell',
weapon: 'bow',
acctack() {
return 'attack with' + elf.weapon
}
}
elf.name
// 'Orwell'
elf.weapon
// 'attack with bow'
가정: elf라는 객체를 만들었는데 다른 name, 다른 weapon을 가지고 있는 객체를 만들고 싶다.
function createElf(name, weapon) {
return {
name,
weapon,
attack() {
return 'attack with' + weapon
}
}
}
const peter = createElf('Peter', 'stones');
peter.attack();
// 'attack with stones'
const sam = createElf('Sam', 'fire');
sam.attack();
// 'attack with fire'
const elfFunctions = {
attack() {
return 'attack with' + this.weapon
}
}
function createElf(name, weapon) {
return {
name,
weapon,
}
}
const peter = createElf('Peter', 'stones');
peter.attack = elfFunctions.attack
peter.attack();
// 'attack with stones';
const elfFunctions = {
attack() {
return 'attack with' + this.weapon
}
}
function createElf(name, weapon) {
let newElf = Object.create(elfFunctions);
newElf.name = name;
newElft.weapon = weapon;
return newElf;
}
const peter = createElf('Peter', 'stones');
peter.attack();
// 'attack with stones'
const sam = createElf('Sam', 'fire');
sam.attack();
// 'attack with fire'
function Elf(name, weapon) {
this.name = name;
this.weapon = weapon;
}
const peter = new Elf('Peter', 'stones');
// this는 peter
peter.attack();
// 'attack with stones'
const sam = new Elf('Sam', 'fire');
// this sam
sam.attack();
// 'attack with fire'
const Elf1 = new Function(
'name',
'weapon',
this.name = name;
this.weapon = weapon;
)
const sarah = new Elf1('Sarah', 'fireworks')
// {name: 'Sarah', weapon: 'fireworks'}
new 키워드를 붙여서 함수를 호출할 때 함수이므로 실행 컨텍스트가 생성되는데 이때 this도 같이 실행컨텍스트에 붙여진다.(모든 함수는 호출될 때 실행컨텍스트가 만들어지고 이 실행컨텍스트는 arguments 객체, this, 스코프체인등으로 구성된다.)
함수가 전역에서 호출될 때 this는 window객체를 가리키게 되지만 new를 붙여 함수를 호출할 경우 실행컨텍스트가 생성될 때 this를 생성자 함수로 만들어질 객체를 가리키게 한다.
Elf는 함수이다. 모든 함수는 prototype property를 가지고 있다.
일반적이 함수의 경우 이 prototype property가 쓸모가 없지만 생성자 함수의 경우 유용하다.
내장 객체 prototype에 다양한 메소들를 저장하는 것 처럼 생성자 함수의 prototype에 다양한 메소드를 저장할 수 있다.
function Elf(name, weapon) {
this.name = name;
this.weapon = weapon;
}
Elf.prototype.attack = funtion() {
return 'attack with' + this.weapon
// this will be the calling object
}
const peter = new Elf('Peter', 'stones');
peter.attack();
// 'attack with stones'
Elf.prototype.attack = () => {
return 'attack with' + this.weapon
}
Elf.prototye.build = function() {
function building() {
return this.name + 'builds a house';
}
return building.bind(this)
}
conole.log(peter.build()())
Elf.prototye.build = function() {
const self = this;
function building() {
return self.name + 'builds a house';
}
return building()
}
conole.log(peter.build())