Trainings/이전 TIL 기록

[TIL] 2020-03-08

태기의삶 2020. 3. 8. 23:54

[노마드 코더]

ReactJS로 웹 서비스 만들기  #3.1 All you need to know about State까지 수강

 

[배운 내용]

this의 값은 함수를 호출하는 방법에서 결정된다.

1. 전역에서 this

console.log(this); // window {...}

this.a = 'A';
console.log(window.a) // 'A'

this.hello = 'world';
console.log(window.hello) // 'world'

cat = "Meow";
console.log(window.cat) // 'Meow'
console.log(cat) // 'Meow'

thist는 기본적으로 전역 객체인 window에 바인딩된다.

 

2. 함수에서의 this

function foo() {
	return this;
}
console.log(foo()); // window {...}

dog = "bow";
function bar () {
	return this.dog;
}
console.log(bar()); // bow;

함수 안에 있는 this가 window객체를 가리키고 있다는 걸 확인할 수 있다.

 

3. call, apply

call, apply를 이용해서 this를 window가 아닌 다른 객체의 속성 값을 사용할 수 있게 할 수 있다.

world = 'world'
function hello () {
	return this.world
}
console.log(hello()); // 'world'

const hello2 = {
	world: 'world~!'
}
console.log(hello.call(hello2)) // 'world~!';
console.log(hello.apply(hello2)) // 'world~!';

처음의 매개변수가 this를 어디 객체에 속하게 할 것인지 결정한다.

call과 apply의 차이점이 있다.

call은 낱개로 전달하고 apply는 배열을 이용해서 매개변수에 전달한다.

// call   somthing.call(thisArgu, parameter1, parmeter2, ...)
// apply  somthing.apply(thisArgu, [parameter1, parmeter2, ...]);
function sum (a, b) {
	return this.one + this.two + a + b;
}
const number = {
	one: 1,
    two: 2,
}
let callResult = sum.call(number, 5, 15);
console.log(callResult) // 23
let applyResult = sum.apply(number, [3, 4]);
console.log(applyResult) // 10

 

4. method에서 this

객체에서 생성한 함수, 메소드에 내부에 있는 this는 그 객체에 할당한다.

const foo = {
  	a: 'A',
	objFunc: function () {
      return this;
	}
}
let result = foo.objFunc();
console.log(result); // {a: 'A', objFunc: ƒ}

const bar = {
	num1: 5,
    num2: 30,
    sum: function () {
		return this.num1 + this.num2
	}
}
result = bar.sum();
console.log(result); // 35

 

메소드 호출도 call과 apply를 이용해서 다른 객체의 속성을 이용할 수 있습니다.

const foo = {
	character: 'a',
  	output: function () {
		return this.character;
	}
}
let normal = foo.output();
console.log(normal); // 'a'

const bar = {
	character: '가'
}
let callResult = foo.output.call(bar);
console.log(callResult); // '가'

 

생성자 함수로 생성한 인스턴스는 만들어진 인스턴스가 this로 결정된다.

const Basicwizard (wand, magic) {
	this.wand = wand;
  	this.magic = magic;
  	this.cast = function () {
		return `Use ${this.magic} with ${this.wand}`;
}

const fireWizard = new Basicwizard('firewand', 'fireball');
console.log(fireWizard.cast()); // Use fireball with firewand