상세 컨텐츠

본문 제목

[자바스크립트] this 바인딩 하는법

카테고리 없음

by esoesmio 2023. 5. 16. 19:45

본문

call 은 그냥 객체 ㅡ 요소 넣고 apply는 객체, [배열요소]

 

ㅣ렇게넣음

 

a = 15;
b = 1555;

function add(c, d) {
    return this.a + this.b + c + d;
}

var o = {a: 1, b: 3};

// 첫 번째 인자는 'this'로 사용할 객체이고,
// 이어지는 인자들은 함수 호출에서 인수로 전달된다.
console.log(add.call(o, 5, 7)); // 16

// 첫 번째 인자는 'this'로 사용할 객체이고,
// 두 번째 인자는 함수 호출에서 인수로 사용될 멤버들이 위치한 배열이다.
console.log(add.apply(o, [10, 20])); // 34

console.log(add(1,2));

 

function f() {
    return this.a;
}

var g = f.bind({a: 'azerty'});

console.log(g()); // azerty

var h = g.bind({a: 'yoo'}); // bind는 한 번만 동작함!

console.log(h()); // azerty

var o = {
    a: 37,
    f: f,
    g: g,
    h: h
};


console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty

 

 

댓글 영역