on
객체지향 프로그래밍 - 객체와함수,call,bind
객체지향 프로그래밍 - 객체와함수,call,bind
Call() 과 bind() 를 사용해서 평범한 함수를 객체의 메소드로 사용할 수 있다.
call()
메소드로 쓸 함수.call(호출에 제공되는 this의 값,인자1,인자2,..)
var kim = {name:'kim', first:10, second:20} var lee = {name:'lee', first:10, second:10} function sum(prefix){ return prefix+(this.first+this.second); } //sum()에 쓰일 this값은 kim console.log("sum.call(kim)", sum.call(kim, '=> ')); // 결과 : sum.call(kim)=>30 //sum()에 쓰일 this값은 lee console.log("lee.call(kim)", sum.call(lee, ': ')); // 결과 : sum.call(kim)=>20
bind()
call과 aplye 는 함수 호출과 동시에 함수 실행한다.
하지만 bind() 함수를 실행하지 않고 바인딩된 새로운 함수를 만든다.
function fnc(prop) { return this[prop]; } const callObj = { hello: 'world' }; const callValue = fnc.call(callObj, 'hello'); //call() 은 바로 함수를 호출한다 console.log(callValue); // 'world'; //bind() 는 this가 바인딩된 새로운 함수를 만든다. const bindValue = fnc.bind(callObj, 'hello'); console.dir(bindValue); //fnc(prop) { // return this[prop]; //} // 바인딩된 함수 실행 console.log(bindValue()); // 'world'
https://www.youtube.com/watch?v=wOiteGyan-I&list;=PLuHgQVnccGMAMctarDlPyv6upFUUnpSO3&index;=25
https://falsy.me/javascript-8-%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EC%9D%98-call-apply-bind%EC%97%90-%EB%8C%80%ED%95%B4-%EC%95%8C%EC%95%84%EB%B4%85%EB%8B%88%EB%8B%A4/
from http://liyang.tistory.com/138 by ccl(A) rewrite - 2021-10-25 23:59:05