Web Devlopment/JavaScript
#14 상속, 프로토타입(Prototype)
키모형
2025. 3. 19. 22:00
반응형
참고 문서 : https://ko.javascript.info/prototype-inheritance
const user = {
name: "Kimo",
hasOwnProperty: function () {
console.log('test')
}
}
console.log(user.name);
console.log(user.hasOwnProperty('name'));
console.log(user.hasOwnProperty('age'));
// 상속, 프로토타입, 클로저
const Bmw = function(color){
const c = color; // this.color을 클로저로 은닉화
this.getColor=function() {
console.log(c);
};
// this.color=color;
}
// 프로토타입 선언방식1
// Bmw.prototype.wheels=4;
// Bmw.prototype.navigation=1;
// Bmw.prototype.drive=function(){
// console.log("drive..");
// };
// Bmw.prototype.stop=function(){
// console.log("Stop!!");
// };
// 프로토타입 선언방식2
Bmw.prototype = {
//construrtor : 방식1은 자동으로 지정되지만, 방식2 에서는 직접 기재해야함
constructor: Bmw,
wheels: 4,
navigator: 1,
drive() {
console.log("drive...");
},
stop() {
console.log("Stop!!");
},
}
// Bmw 생성자 함수로 객체생성
const x5 = new Bmw("red");
const z4 = new Bmw("blue");
console.log(x5.color); // undefined , 클로저로 접근제한
x5.getColor();
x5.drive();
x5.stop();
// red
// drive..
// Stop!!
// Bmw를 상속한 객체인지 검사
console.log(z4 instanceof Bmw);
console.log(z4.constructor === Bmw);
// true
// true
반응형