this

hanyoko·2023년 6월 21일
0

JAVASCRIPT

목록 보기
29/32
post-thumbnail

this

사용되는 위치에 따라 this 키워드에 바인드 된 객체가 달라진다.

  • web에서는 글로벌 객체인 window가 반환되어 있다.
  • 객체.메소드() 에서는 객체를 반환한다.
  • HTML DOM요소 에 이벤트 발생시 이벤트를 발생한 HTML DOM 요소를 반환한다.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <li onclick = "printLi(this)">list1</li>
    <li onclick = "printLi(this)">list2</li>
    <li onclick = "printLi(this)">list3</li>
    <li onclick = "printLi(this)">list4</li>
    <select name = "userNum" id  ="userNum" onchange = "selectFun(this)">
        <option value = "1">1입니다.</option>
        <option value = "2">2입니다.</option>
        <option value = "3">3입니다.</option>
    </select>
    <script>
        function printLi(li){
            console.log(li.innerHTML);
        }
      	// 클릭한 li에 따라 innerHTML인 list1 / list2 / list3 / list4 가 출력
      
        function selectFun(select){
            console.log(select.value);
        }
      
      	// select를 선택하면에 value인 1 / 2 / 3이 출력	
      
        let person = {
            firstName : "John",
            lastName : "Doe",
            fullName : function(){
                return this.firstName + " " + this.lastName;
            }
        }
        console.log(person.fullName());
      	// object의 firstName과 object의 lastName을 반환하여 더한 값을 fullName key의 value에 저장한다.      
      
        // person.fullName()

        //rest parameter
        function add(...rest){
            let sum = 0;
            rest.forEach(num => {
                sum = sum + sum;
            })
            return sum;
        }
        let result1 = add(1,2,3);
        let result2 = add(1,2,3,4);
        let result3 = add(1,2,3,4,5);
        console.log(result1);
        console.log(result2);
        console.log(result3);

        // const hello3 = (name) => {return "hello" + name};
        // const hello3 = name => "hello" + name; //이렇게 생략가능
        const hello3 = name => `hello ${name}`;
        let str1 = "green" 
        // console.log(hello3("aa"));
        console.log("안녕하세요" + str1 + "씨~~~~");
        console.log(`안녕하세요 ${str1}씨~~~~`);
    </script>
</body>
</html>

this 바인딩

this를 특정 값으로 지정할 수 있는 메소드

call

함수명.call(변수,함수의 매개변수)

this를 함수에서 사용하고 싶을때, 아래와 같이 전달한다.

let stu = {
	name: "B",
  	age: 30
}
function printName(){
  console.log(this.name)
}

printName()
// ""
printName.call(stu)
// "B"

function objUpdate(name, age){
	this.name = name;
  	this.age = age;
}

objUpdate.call(student1, "green", 30);
console.log(stu)
// "green"

apply

함수명.call (변수,함수의 매개변수)

this를 함수에서 사용하고 싶을때, 아래와 같이 전달한다.
함수에 매개변수를 입력할 때, 배열로 입력한다.

objUpdate.apply(student1, ["green", 30]);
console.log(stu)
// "green"
// apply는 배열을 펼쳐넣는다.
// 때문에 apply를 지정할 때에는 numArr와 같이 지정해야한다.
// call은 배열을 펼쳐넣지 않으므로 ...numArr로 작성해야한다.

const numArr = [1, 2, 3, 4, 5];
let maxNumber = Math.max.apply(null, numArr);
let maxNumber2 = Math.max.call(null, ...numArr);

bind

함수.bind(변수)

this의 값을 영구적으로 변경한다.

const aa={
	 x:50
}
const newFun= aa.getX;
const nnewFun= newFun.bind(aa);
//newFun= function(){return this.x;}

console.log(newFun());
// undefined
console.log(nnewFun());
// 50
함수.bind(this)
// this를 "나 자신"으로 지정한다.

0개의 댓글