-
자바스크립트 prototype chain 상속JavaScript 2023. 2. 7. 22:09
프로토타입을 이용한 상속
let objFunc = function() { this.one = "one"; this.two = "two"; } let obj = new objFunc(); objFunc.prototype.two = "one"; objFunc.prototype.three = "three"; console.log(obj.one); // one console.log(obj.two); // one console.log(obj.three); // three console.log(obj.check); // undefined기본적인 prototype chain
function chain1() {} chain1.prototype.foo = "bar"; var chain2 = new chain1(); chain2.prop = "value"; console.log("chain2.prop: " + chain2.prop); // value console.log("chain2.foo: " + chain2.foo); // bar console.log("chain1.prop: " + chain1.prop); // undefined console.log("chain1.foo: " + chain1.foo); // undefined console.log("chain1.prototype.prop: " + chain1.prototype.prop); // undefined console.log("chain1.prototype.foo: " + chain1.prototype.foo); // barchain2의 prototype은 chain1의 prototype이다.
chain2에서 foo를 찾으려고 한다면?
1. chain2의 속성에서 찾아보고 있다면 바로 사용한다.
2. chain2의 속성에 없다면 chain1으로 가서 찾는다.
3. 만약에 chain1에 있다면 사용한다.
4. 만약에 chain1에 없다면 undefined를 반환하며 prototype chain을 종료한다.'JavaScript' 카테고리의 다른 글
자바스크립트 상황별 this (0) 2023.02.07 자바스크립트 __proto__ / prototype 차이 (0) 2023.02.07 자바스크립트 call, apply, bind (0) 2023.02.07 자바스크립트 setTimeout, setInterval, clearTimeout, clearInterval (0) 2023.01.30 자바스크립트 함수, 함수 호출의 차이 (0) 2022.11.24