Hello, Dino
객체(Object) 본문
객체(Object): 고양이 🐱
Property
: name, age, weight, color
Method
: eat, sleep, mew
var cat = {
// property
name: "Nabi", age:1, weight: 1.2, color: "yellow"
// method
, eat: Function(food){return "Eat: " + food; }
, sleep: Function(){return "Sleep ...";}
, mew: Function(){return "Mew ...";}
};
Object Property & Method 참조
// property
cat["name"];
cat.name;
// method
cat.eat("food");
※ Object Method 참조 시 주의 사항
Object Method 참조 시 Method Name 뒤 ()를 붙이지 않으면, Method가 아닌 Property 자체를 참조하게 된다.
따라서 괄호 없이 Method를 참조하는 경우 Method 자체가 return된다.
만약, 수 많은 고양이 객체가 필요하다면... 🤔
var cat1 = {
name: "Nabi", age:1, weight: 1.2, color: "yellow"
, eat: Function(food){return "Eat: " + food; }
, sleep: Function(){return "Sleep ...";}
, mew: Function(){return "Mew ...";}
};
var cat2 = {
name: "Yojo", age:1, weight: 1.5, color: "black"
, eat: Function(food){return "Eat: " + food; }
, sleep: Function(){return "Sleep ...";}
, mew: Function(){return "Mew ...";}
};
var cat3 = {
name: "Samsic", age:2, weight: 3, color: "yellow"
, eat: Function(food){return "Eat: " + food; }
, sleep: Function(){return "Sleep ...";}
, mew: Function(){return "Mew ...";}
};
😱 중복 코드가 너무 많이 발생한다. 그렇기 때문에 상속(inheritance)을 사용하여 재사용 하자
상속(inheritance) & 프로토타입(ProtoType)
C#, Java와 다르게 Javascript는 프로토타입 기반이기 때문에 객체 지향 언어와는 상속의 의미가 살짝 다르다.
Javascript는 현재 존재하고 있는 객체를 프로토타입으로 사용하여, 해당 객체를 복사하여 재사용하는 것을
상속이라 하며, 상속되는 정보를 제공하는 객체를 프로토타입이라고 한다.
프로토타입 생성
// 관례상 객체 생성자 함수의 이름의 첫 문자는 대문자로 작성한다.
function Cat (name, age, weight, color){
// ※ this는 객체 그 자신을 가리킨다.
this.name = name;
this.age = age;
this.weight = weight;
this.color = color;
this.eat = function(food){return "Eat: " + food; };
this.sleep = function(){return "Sleep ...";};
this.mew = function(){return "Mew ...";};
};
객체 프로퍼티 및 메소드 추가
var cat_nabi = new Cat("Nabi", 1, 1.2, "yellow");
cat_nabi.family = "코리아숏헤어";
cat_nabi.pley = function(){returb "Play ...";};
※ 객체에 새롭게 추가된 프로퍼티와 메소드는 해당 객체에서만 사용할 수 있다.
프로토타입 프로퍼티 및 메소드 추가, 삭제
이미 생성된 프로토타입에 새로운 프로퍼티를 추가하거나 기존 프로퍼티를 삭제하고 싶을 때는 어떻게 해야할까?
// 프로토타입 프로퍼티 추가
Cat.prototype.family = "코리아숏헤어";
Cat.prototype.play = function(){return "Play ...";};
var cat = new Cat("nabi", 1, 1.2, "yellow");
cat.pley();
// 프로토타입 프로퍼티 삭제
delete Cat.play;
Reference
'Web > JavaScript' 카테고리의 다른 글
Node (1) | 2020.03.09 |
---|---|
문서 객체 모델 (DOM) (0) | 2020.03.09 |