typescript this

BackEnd_Ash.log·2021년 8월 11일
0

typescript

목록 보기
10/17

to understand this in TypeScript , you should be understand Javascript this
ok?

if you want korean language blog
https://velog.io/@ash3767/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-this

📌 arrow ==> static

👉 function

function Counter(){
	this.value = 0;
	this.add = amount => {
		this.value +=amount;
	};
}

const counter = new Counter(); // 인스턴스 생성 
console.log("counter :",counter.value); // 0
counter.add(5);
console.log("counter :",counter.value); // 5
const add = counter.add;
add(5); 
// 화살표 함수의 this 는 화살표 함수가 생성될 당시의 this 를 가리키게 된다.
// 화살표 함수가 생성될 당시라는것은 이 함수의 this 를 가리키게 된다.
// 즉 화살표 함수의 this 는 이 화살표 함수가 생성될 당시의 this 로 고정이 되기 때문에 , 
// 정적이라고 할 수 있다. 즉 호출하는 주체가 누구인지는 상관이 없게된다.
// 이것은 class 여도 같다. 
console.log("counter :",counter.value); // 10

when called using the new keyword, this in the function Counter points to the counter object.

so you can called value , add

👉 class

class Counter{
	value = 0;
	add = amount => {
		this.value +=amount;
	};
}

const counter = new Counter(); // 인스턴스 생성 
console.log("counter :",counter.value); // 0
counter.add(5);
console.log("counter :",counter.value); // 5
const add = counter.add;
add(5); 
console.log("counter :",counter.value); // 10

this is always points to the object of Counter3 class

📌 normal ==> dynamic

👉 function

function Counter2 (){
	this.value =0;
	this.add = function(amount){
		this.value += amount;
		// console.log(this === global);
	}
}

const counter2 = new Counter2();
console.log("counter2 : ",counter2.value); // 0
counter2.add(5);
console.log("counter2 : ",counter2.value); // 5
const add2 = counter2.add;
add2(5); 
// add2 가 호출해서 인자를 넣을때 this 가 가리키는것이 counter2 가 아니라서 10 이 아니라 5이다 
// 전역객체를 가리키게 된다. 브라우저에서는 window 객체를 가리키게 된다.
// 지금은 node 환경이라서 global 객체를 가리키게 된다.
// 일반함수는 호출될 당시의 상황에 따라서 this 가 바뀌기 때문에 , 
// 동적이라고 할 수 있다.
console.log("counter2 : ",counter2.value); // 5
  • the subject that called counter2.add(5) exists.
  • the subject that called add2(5) not exists.
    ==> it points to the global object.

normal function that it changes according to the situation at the time of the call

so we call this dynamic.

but

arrow function that is not changes according to the situation at the time of the call

so we call this static.

profile
꾸준함이란 ... ?

0개의 댓글