프로토타입 확인
let obj = {
name:'홍길동',
score:90
};
console.log(obj.valueOf()); // obj에는 valueOf()가 없지만 동작함 valueOf()는 상위객체에서 물려받음
console.log(obj.__proto__===Object.prototype);
//__proto__: 객체의 부모를 나타내는 프로토타입으로 부모에게 물려 받은 정보를 가지고 있습니다
//prototype: 자신의 프로토 타입 객체로 물려줄 프로토타입 정보를 가지고있음
function User(name){
this.name = name;
};
let u = new User('이자바');//객체를 생성
console.dir(User); //prototype 프로퍼티가 존재
console.log(u);//prototype 프로퍼티가 없음
console.log(u.__proto__===User.prototype);//true
생성자 에 추가
// 생성자 함수에 추가하는 프로퍼티나 메소드 : 프로토타입에 추가하므로 생성자를 통해 생성된모든객체에 적용
// 프로토타입 : 객체는 부모 객체의 프로퍼티나 메소드를 상속 받아 사용할 수 있으며 ,
// 이러한 부모 객체를 프로토 타입객체 또는 프로토 타입이라 합니다
function User(name){
this.name = name;
this.age = 20;
this.state = ()=> this.age >= 19 ? '성인' : '미성년자';
}
let obj = new User('김자바');
console.log(obj.age,obj.state());
프로토타입 추가
//prototype 프로퍼티 : 생성자에 존재 생성자로 생성되는 객체에 물려줄 프로퍼티와 메소드를 가지고 있음
function User(name,age){
this.name = name;
this.age = age;
}
//객체에 물려줄 값,함수
User.prototype.score = 80;// 프로토타입 추가
User.prototype.state = function(){
return this.age>=19?'성인':'미성년자';
};
let obj = new User('자바',20);
console.log(obj.name,obj.score,obj.state());
let obj2 = new User('스프링',17);
console.log(obj2.name,obj2.score,obj2.state());
// Date 내장 객체에 weekday 라는 메소드를 추가하여 요일출력
Date.prototype.weekday = function(){
let week = ['일','월','화','수','목','금','토'];
return week[this.getDay()];
};
var now = new Date();
console.log(now.weekday());