Node JS 中的原型继承
Prototypal Inheritence in Node JS
来自经典继承背景(C#、Java 等),我正在努力使用原型方法来实现它。
我也不了解基础知识。请在以下代码块中解释并纠正我。
var util = require ('util');
function Student(choiceOfStream) {
this.choiceOfStream = choiceOfStream;
}
Student.prototype.showDetails = function() {
console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}
function ScienceStudent() {
Student.call(this,"Science");
}
function ArtsStudent() {
Student.call(this,"Arts");
}
util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
var ArtsStudent = new ArtsStudent();
var ScienceStudent = new ScienceStudent();
ScienceStudent.prototype.MajorSubject = "Math";
ArtsStudent.prototype.MajorSubject = "Literature";
console.log(ArtsStudent.showDetails());
console.log(ScienceStudent.showDetails());
但我得到的错误是
我错过了什么?
没有标准 this.super_
属性 所以我不确定你从哪里得到的。如果您正在使用 util.inherits()
,您可以在 nodejs doc for util.inherits()
.
中看到一个很好的简单示例来说明如何使用它
而且,您的代码可以这样工作:
var util = require ('util');
function Student(choiceOfStream) {
this.choiceOfStream = choiceOfStream;
}
Student.prototype.showDetails = function() {
console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}
function ScienceStudent() {
Student.call(this, "Science");
this.majorSubject = "Math";
}
function ArtsStudent() {
Student(this,"Arts");
this.majorSubject = "Literature";
}
util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
仅供参考,在 ES6 语法中,有一个 super
关键字,它是声明 Javascript 继承(仍然是原型)的新方法的一部分,您可以阅读 here。
来自经典继承背景(C#、Java 等),我正在努力使用原型方法来实现它。 我也不了解基础知识。请在以下代码块中解释并纠正我。
var util = require ('util');
function Student(choiceOfStream) {
this.choiceOfStream = choiceOfStream;
}
Student.prototype.showDetails = function() {
console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}
function ScienceStudent() {
Student.call(this,"Science");
}
function ArtsStudent() {
Student.call(this,"Arts");
}
util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
var ArtsStudent = new ArtsStudent();
var ScienceStudent = new ScienceStudent();
ScienceStudent.prototype.MajorSubject = "Math";
ArtsStudent.prototype.MajorSubject = "Literature";
console.log(ArtsStudent.showDetails());
console.log(ScienceStudent.showDetails());
但我得到的错误是
我错过了什么?
没有标准 this.super_
属性 所以我不确定你从哪里得到的。如果您正在使用 util.inherits()
,您可以在 nodejs doc for util.inherits()
.
而且,您的代码可以这样工作:
var util = require ('util');
function Student(choiceOfStream) {
this.choiceOfStream = choiceOfStream;
}
Student.prototype.showDetails = function() {
console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}
function ScienceStudent() {
Student.call(this, "Science");
this.majorSubject = "Math";
}
function ArtsStudent() {
Student(this,"Arts");
this.majorSubject = "Literature";
}
util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
仅供参考,在 ES6 语法中,有一个 super
关键字,它是声明 Javascript 继承(仍然是原型)的新方法的一部分,您可以阅读 here。