이 기사는 JavaScript 프로토 타입 체인 상속의 사용을 분석합니다. 참조를 위해 공유하십시오. 특정 분석은 다음과 같습니다.
다음과 같이 코드를 복사합니다. function shape () {
this.name = 'shape';
this.tostring = function () {
이 this.name;
}
}
함수 twodshape () {
this.name = '2d Shape';
}
기능 삼각형 (측면, 높이) {
this.name = '삼각형';
this.side = 측면;
this.height = 높이;
this.getArea = function () {
이 this.side*this.height/2;
};
}
/ * 상속 */
twodshape.prototype = new Shape ();
Triangle.prototype = new Twodshape ();
객체의 프로토 타입 속성을 완전히 다시 작성하면 때로는 물체의 생성자 속성에 부정적인 영향을 미칩니다.
따라서 관련 상속 관계 설정을 완료 한 후에는 이러한 객체의 Const 속성을 그에 따라 재설정하는 것이 매우 좋은 습관입니다. 아래 그림과 같이 :
코드 사본은 다음과 같습니다.
Triangle.prototype.constructor = 삼각형;
고쳐 쓰기:
다음과 같이 코드를 복사하십시오 : function shape () {}
shape.prototype.name = 'shape';
shape.prototype.tostring = function () {
이 this.name;
}
함수 twodshape () {}
twodshape.prototype = new Shape ();
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name = '2d Shape';
기능 삼각형 (측면, 높이) {
this.side = 측면;
this.height = 높이;
}
Triangle.prototype = 새로운 Twodshape;
Triangle.prototype.constructor = 삼각형;
Triangle.prototype.name = '삼각형';
triangle.prototype.getArea = function () {
이 this.side*this.height/2;
}
다시 작성 (값 패스 대신 참조 패스) :
다음과 같이 코드를 복사하십시오 : function shape () {}
shape.prototype.name = 'shape';
shape.prototype.tostring = function () {
이 this.name;
}
함수 twodshape () {}
twodshape.prototype = shape.prototype;
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name = '2d Shape';
기능 삼각형 (측면, 높이) {
this.side = 측면;
this.height = 높이;
}
Triangle.prototype = twodshape.prototype;
Triangle.prototype.constructor = 삼각형;
Triangle.prototype.name = '삼각형';
triangle.prototype.getArea = function () {
이 this.side*this.height/2;
}
효율성이 향상되지만 이러한 방법은 부작용이 있습니다. 값 통과가 아닌 참조 통과이므로 "부모 객체"의 이름 값이 영향을받습니다.
자식 객체와 부모 객체는 동일한 객체를 가리 킵니다. 따라서 자식 객체가 프로토 타입을 변경하면 부모 객체도 즉시 변경됩니다.
다시 작성 (임시 생성자 사용) :
다음과 같이 코드를 복사하십시오 : function shape () {}
shape.prototype.name = 'shape';
shape.prototype.tostring = function () {
이 this.name;
}
함수 twodshape () {}
var f = function () {}
f. prototype = shape.prototype;
twodshape.prototype = new f ();
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name = '2d Shape';
기능 삼각형 (측면, 높이) {
this.side = 측면;
this.height = 높이;
}
f. prototype = twodshape.prototype;
Triangle.prototype = new f ();
Triangle.prototype.constructor = 삼각형;
Triangle.prototype.name = '삼각형';
triangle.prototype.getArea = function () {
이 this.side*this.height/2;
}
효율성이 향상되지만 이러한 방법은 부작용이 있습니다. 값 통과가 아닌 참조 통과이므로 "부모 객체"의 이름 값이 영향을받습니다.
자식 객체와 부모 객체는 동일한 객체를 가리 킵니다. 따라서 자식 객체가 프로토 타입을 정렬하고 수정하면 부모 객체도 즉시 변경됩니다.
이 기사가 모든 사람의 JavaScript 프로그래밍에 도움이되기를 바랍니다.