在原型继承的一个简单示例中,我想将Person
对象设置为Student
对象的父类,但我不想在使用新关键字时使用设置Student
类的原型,因为这是错误的。但不知何故,这段代码并不起作用。有帮助吗?
var Person = function(name) {
var that = this;
this.name = name;
var _log = function() {
console.log("Hello", that.name)
};
return {
log: _log
};
};
var Student = function(name) {
Person.call(this, name);
var _getCollegeName = function() {
console.log("MIT")
};
return {
getCollegeName: _getCollegeName
};
};
Student.prototype = Object.create(Person);
//Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class
var s = new Student("Soham");
s.log();
//s.getCollegeName();
答案 0 :(得分:1)
您可以将getCollegeName
设置为Person()
来电的属性,返回Person
对象
var Person = function(name) {
var that = this;
this.name = name;
var _log = function() {
console.log("Hello", that.name)
};
return {
log: _log
};
};
var Student = function(name) {
var p = Person.call(this, name);
var _getCollegeName = function() {
console.log("MIT")
};
p.getCollegeName = _getCollegeName;
return p
};
Student.prototype = Object.create(Person);
//Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class
var s = Student("Soham");
s.log();
s.getCollegeName();