TIL 210227

Jebbit-koi·2021년 2월 27일
0

TIL

목록 보기
29/30

OOP 정리

//this
console.log("this is this");

let cat = {
  animal: "cat",
  first: 0.5,
  second: 1.7,
  sum: function () {
    return this.first + this.second;
  },
};

console.log("cat.sum() :", cat.sum(), "kg");

//constructor // 만들고 초기화해준다
console.log("constructor");
function Cat(name, age, first, second) {
  this.name = name;
  this.age = age;
  this.first = first;
  this.second = second;
  //   this.sum = function () {
  //     return this.first + this.second;
  //   };
}

let koi = new Cat("koi", 0.5, 0.6, 1.7);
let honeybread = new Cat("honeybread", 3, 2.5, 3.4);
// console.log("koi.sum()", koi.sum());
// console.log("honeybread.sum()", honeybread.sum());

//prototype
//매번 함수를 생성해줘야한다. 메모리가 힘들어한다..
Cat.prototype.sum = function () {
  return "prototype :" + (this.first + this.second);
};

let coco = new Cat("coco", 2, 0.4, 5);
coco.sum = function () {
  return "this :" + (this.first + this.second);
};
let mandoo = new Cat("mandoo", 2, 1.3, 2);
console.log("coco.sum()", coco.sum()); // 객체가 직접 함수를 가지고 있는지 찾는다
console.log("mandoo.sum()", mandoo.sum()); // 없으면 생성자Cat의 prototype을 참조한다

0개의 댓글

Powered by GraphCDN, the GraphQL CDN