[英]How to call a constructor method of Parent class from child prototype in javascript?
[英]In JavaScript, how do I inherit from a parent class in child class using a single “.prototype” block?
例如:
function Person() {
//person properties
this.name = "my name";
}
Person.prototype = {
//person methods
sayHello: function() {
console.log("Hello, I am a person.");
}
sayGoodbye: function() {
console.log("Goodbye");
}
}
function Student() {
//student specific properties
this.studentId = 0;
}
Student.prototype = {
//I need Student to inherit from Person
//i.e. the equivalent of
//Student.prototype = new Person();
//Student.prototype.constructor = Person;
//student specific methods
//override sayHello
sayHello: function() {
console.log("Hello, I am a student.");
}
}
我知道我可以使用以下方法實現此目的:
function Student() {
this.studentId = 0;
}
Student.prototype = new Person();
Student.prototype.constructor = Person;
Student.prototype.sayHello = function () {
console.log("Hello, I am a student.");
}
但我想繼續使用第一個示例中的樣式,並盡可能將所有類方法定義在單個“ .prototype”塊中。
在StackOverflow上查看以下答案: https ://stackoverflow.com/a/17893663/783743
該答案介紹了原型類同構的概念。 簡單地說,可以使用原型對象為類建模。 以下代碼摘自上述答案:
function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
使用以上方法,我們可以實現Person
,如下所示:
var Person = CLASS({
constructor: function () {
this.name = "my name";
},
sayHello: function () {
console.log("Hello, I am a person.");
},
sayGoodbye: function () {
console.log("Goodbye");
}
});
但是,繼承需要做一些額外的工作。 因此,讓我們對CLASS
函數進行一些修改:
function CLASS(prototype, base) {
switch (typeof base) {
case "function": base = base.prototype;
case "object": prototype = Object.create(base, descriptorOf(prototype));
}
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
我們還需要為CLASS
定義descriptorOf
函數:
function descriptorOf(object) {
return Object.keys(object).reduce(function (descriptor, key) {
descriptor[key] = Object.getOwnPropertyDescriptor(object, key);
return descriptor;
}, {});
}
現在我們可以如下創建Student
:
var Student = CLASS({
constructor: function () {
this.studentId = 0;
},
sayHello: function () {
console.log("Hello, I am a student.");
}
}, Person);
親自觀看演示: http : //jsfiddle.net/CaDu2/
如果您在理解代碼方面需要任何幫助,請隨時與我聯系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.