[객체지향] __proto__/ call / bind / create

트릴로니·2021년 11월 25일

자바스크립트

목록 보기
10/31

proto

let superObj = {
  superVal: 'super'
}
let subObj = {
  subVal: 'sub'
}
subObj.__proto__ = superObj;
console.log(subObj.superVal) // 'super'

📌proto: 객체를 다른 객체의 자식 객체로 만듦

  • subObj.proto = superObj;
    • subObj의 원형이 무엇인지 링크를 걸어줌

call

let kim = {
  name: 'kim',
  first: 10,
  second: 20,
}
let lee = {
  name: 'lee',
  first: 10,
  second: 10,
}
function sum(prefix){
  return prefix + (this.first + this.second);
}
console.log(sum.call(kim, 100));//130
console.log(sum.call(lee, 1000));//1020

📌 fn.call()

  • 첫번째 인자: this를 지정
  • 나머지 인자: 지정하고 싶은 나머지 인자 지정

bind

let kim = {
  name: 'kim',
  first: 10,
  second: 20,
}
let lee = {
  name: 'lee',
  first: 10,
  second: 10,
}
function sum(prefix){
  return prefix + (this.first + this.second);
}

console.log(sum.call(kim, 100));
console.log(sum.call(lee, 1000));

let newKim = sum.bind(kim, 3000);
console.log(newKim())

📌fn.bind()

  • 첫번째 인자: this 지정
  • 나머지 인자: 지정하고 싶은 나머지 인자 지정
  • newKim은 kim을 this로 하는 새로운 함수

🔎 bind vs call

  • call은 실행할 때 함수의 this의 값을 바꾸고
  • bind는 this가 지정된 새로운 함수를 만듦

create

let superObj = {superVal: 'super'}
let subObj = Object.create(superObj)
subObj.subVal = 'sub';
debugger;
console.log(subObj.subVal);
console.log(subObj.superVal);
subObj.superVal= 'sub';
console.log(superObj.superVal)

let kim = {
  name: 'kim',
  first: 10, second: 20,
  sum: function(){return this.first + this.second}
}

let lee = Object.create(kim);
lee.name = 'lee';
lee.first = 10;
lee.second = 10;
lee.avg = function(){
  return (this.first + this.second)/2;
} 
console.log(lee.sum())
console.log(lee.avg())

📌subObj = object.create(superObj)

  • subObj는 superObj를 부모로 하는 새로운 객체로 새로 만들어짐

0개의 댓글