JavaScript? - > prototype기반의 언어.
ES5까지는 class가 없었음. > sudo-classical
ES6부터 calss 지원(하지만 그렇다고 해서 JS가 프로토타입 기반의 언어인 것은 변하지 않았음.)
__proto__, constructor, prototype 이 각각 어떤 관계를 가지고 있는가?
What is Object.create?
ES6 class, super keyword 에 대해서
Prototype 상속
_proto_ : prototype을 확인할 수 있다.
function Human(name) {
this.name = name;
}
let steve = new Human('steve');
steve.__proto__ === Human.prototype; //true
아래 코드가 실행되는 이유?
var Human = function(name) {
this.name = name;
}
Human.prototype.sleep = function() {};
var steve = new Human('steve');
steve.toString(); // [object Object]
// Human.__proto__에는 toString()이 없지만 Human의 기본형인 Object에는 tostring()이 존재한다.
//(모든 객체는 object를 상속받는다.)
// steve.__proto__.__proto__ === Object.__proto__; // true
JS에서 상속 구현하기
._proto_에 .prototype대입 : 상속이 아님
var Human = function(name) {
this.name = name;
}
Human.prototype.sleep = function() {
console.log('zzz');
}
var Student = function() {}
Student.prototype.learn = function() {
console.log('배우는 중...');
}
var student1 = new Student();
student1.__proto__ = Human.prototype; //Error는 안생기지만 이렇게 쓰지 않는 것이 좋다.
// __proto__프로퍼티는 참조의 용도로만 사용해야 한다. (변형하지 않아야 함)
// 그리고 위와 같이 쓰면 student1변수 하나만의 prototype만 변하는 것이기 때문에 Student에 할당한 것이 아니다.
.prototype에 .prototype 대입 : 상속이 아님.
var Human = function(name) {
this.name = name;
}
Human.prototype.sleep = function() {
console.log('zzz');
}
var Student = function() {}
Student.prototype.learn = function() {
console.log('배우는 중...');
}
var student1 = new Student();
//위와 같이 쓰는건 MyArray.prototype이 Array.prototype을 참조하는것이 되어버려서 할당이 아니다.
Object.create()사용
var Human = function(name) {
this.name = name;
}
Human.prototype.sleep = function() {
console.log('zzz');
}
var Student = function(name) {
Human.call(this, name); //혹은 apply 사용
//현재 Student의 prototype에 constructor가 없는 상태이다.
//그렇기 때문에 Human의 constructor를 받아와야 한다.
//Human의 constructor는 Student의 상태를 모르기 때문에 call이나 apply를 사용해서 현재의 this를 넣어줘야 한다.
}
Student.prototype = Object.create(Human.prototype);
Student.prototype.constructor = Student;
Student.prototype.learn = function() {
console.log('배우는 중...');
}
var student1 = new Student('first');
student1.learn(); //배우는 중...
student1.sleep(); //zzz
'Codestates > Full IM' 카테고리의 다른 글
BeesBeesBees (0) | 2020.07.30 |
---|---|
Inheritance patterns (0) | 2020.07.30 |
Object Oriented Programming + Instantiation (0) | 2020.07.29 |
Data Structure Time Complexity (0) | 2020.07.27 |
Data Structure Graph, Tree, BST (0) | 2020.07.27 |