#19. call, apply, bind

Seulyi Yoo·2022년 7월 13일
0

javascript grammar

목록 보기
19/20
post-thumbnail

함수 호출 방식과 관계없이 this를 지정할 수 있음

call

const mike = {
  name: "Mike"
};

const tom = {
  name: "Tom"
};

function showThisName(){
  console.log(this.name);
};

showThisName(); // "", this -> window
showThisName.call(mike); // "Mike", this -> mike
showThisName.call(tom); // "Tom", this -> tom

function update(birthday, occupation) {
  this.birthday = birthday;
  this.occupation = occupation;
};

update.call(mike, 1999, 'singer');
console.log(mike); // {name: "Mike", birthday: 1999, occupation: 'singer'}, this -> mike

update.call(tom, 2002, 'teacher');
console.log(tom); // {name: "Tom", birthday: 2002, occupation: 'teacher'}, this -> Tom

apply : 배열로 받음

const mike = {
  name: "Mike"
};

const tom = {
  name: "Tom"
};

function showThisName(){
  console.log(this.name);
};

showThisName(); // "", this -> window
showThisName.call(mike); // "Mike", this -> mike
showThisName.call(tom); // "Tom", this -> tom

function update(birthday, occupation) {
  this.birthday = birthday;
  this.occupation = occupation;
};

update.apply(mike, [1999, 'singer']);
console.log(mike); // {name: "Mike", birthday: 1999, occupation: 'singer'}, this -> mike

update.apply(tom, [2002, 'teacher']);
console.log(tom); // {name: "Tom", birthday: 2002, occupation: 'teacher'}, this -> Tom
const nums = [3, 10, 1, 6, 4];
const minNum = Math.min(...nums);
const maxNum = Math.max(...nums);

console.log(minNum); // 1
console.log(maxNum); // 10

------------------------------------------

const nums = [3, 10, 1, 6, 4];
const minNum = Math.min.apply(null, nums);
// = Math.min.applay(null, [3, 10, 1, 6, 4]);
const maxNum = Math.max.apply(null, nums);
// = Math.max.applay(null, [3, 10, 1, 6, 4]);

console.log(minNum); // 1
console.log(maxNum); // 10

------------------------------------------

const nums = [3, 10, 1, 6, 4];
const minNum = Math.min.call(null, ...nums);
// = Math.min.applay(null, 3, 10, 1, 6, 4);
const maxNum = Math.max.call(null, ...nums);
// = Math.max.applay(null, 3, 10, 1, 6, 4);

console.log(minNum); // 1
console.log(maxNum); // 10

bind

const mike = {
  name: "Mike"
};

function update(birthday, occupation) {
  this.birthday = birthday;
  this.occupation = occupation;
};

const updateMike = update.bind(mike);

updateMike(1980, "police");
console.log(mike); // {name: "Mike", birthday: 1980, occupation: "police"}
const user = {
  name: "Mike",
  showName: function(){
    console.log(`hello, ${this.name}`);
  }
}
user.showName(); // "hello, Mike"

let fn = user.showName;

fn(); //"hello,"

fn.call(user); // "hello, Mike"
fn.apply(user); // "hello, Mike"

let boundFn = fn.bind(user);
boundFn(); // "hello, Mike"
profile
성장하는 개발자 유슬이 입니다!

0개의 댓글