prototype기반의 언어.
ES5까지는 class가 없었음. > sudo-classical
ES6부터 calss 지원(하지만 그렇다고 해서 JS가 프로토타입 기반의 언어인 것은 변하지 않았음.)
__proto__
: 프로토타입을 확인할 수 있다.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
.__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 Immersive Course
YOU DON'T KNOW JS(this와 객체 프로토타입, 비동기와 성능) - 카일 심슨 [한빛미디어]