>  기사  >  웹 프론트엔드  >  Node.js 시뮬레이션 클래스 상속 작은 example_javascript 기술

Node.js 시뮬레이션 클래스 상속 작은 example_javascript 기술

WBOY
WBOY원래의
2016-05-16 18:22:54906검색
코드 복사 코드는 다음과 같습니다.

//프로토타입 상속을 사용하고, middle 의 프로토타입 속성으로 임시 객체의 프로토타입 속성은 상위 클래스의 프로토타입을 가리킵니다.
//모든 하위 클래스와 상위 클래스 프로토타입 속성이 동일한 객체를 가리키는 것을 방지합니다
//In. 이렇게 하면 하위 클래스의 프로토타입 속성이 수정될 때 다른 하위 클래스 및 상위 클래스에 영향을 미치지 않습니다.
function extend(Child, Parent) {
var F = function(){};F. 프로토타입 = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child.
Child.base = Parent.prototype; function Parent(name)
{
this.aa = 123;
this.getName = function() {return name;} //비공개 멤버를 시뮬레이션하려면 클로저를 사용하세요.
this.setName = function (값){이름=값;};
}
Parent.prototype.print = function(){alert("print!");}
Parent.prototype.hello = function()
{
alert(this.getName() "Parent ")
};

function Child(이름, 나이)
{
Parent.apply(this, 인수) ;//상위 클래스 생성자를 호출하여 상위 클래스에서 정의한 속성을 상속합니다.
this.age = age
}
extend(Child,Parent) //Inherit Parent

Child.prototype.hello = function() //부모 클래스의 hello 메소드를 재정의합니다.
{
alert(this.getName() "Child")

Parent.prototype.hello. apply(this,arguments); //동일한 이름으로 상위 클래스 메소드 호출
//하위 클래스 메소드
Child.prototype.doSomething = function(){ Alert(this.age "Child doSomething"); };

var p1 = new Child("xhan", 22);

var p2 = new Child("xxx",33);

p1.hello();
p2.hello();

p1 .doSomething(); //하위 클래스 메서드
p1.print(); >alert(p1 인스턴스ofChild); //참
alert(p1 인스턴스of부모); //참

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.