如何在不使用 new 关键字的情况下设置原型函数
How can I set a prototype function without using the new keyword
在原型继承的一个简单示例中,我想将 Person
对象设置为 Student
对象的父对象 class,但我不想使用 new 关键字在为 Student
class 设置原型时,因为这是错误的。但不知何故这段代码不起作用。有什么帮助吗?
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();
您可以将 getCollegeName
设置为 Person()
调用的 属性,return 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();
在原型继承的一个简单示例中,我想将 Person
对象设置为 Student
对象的父对象 class,但我不想使用 new 关键字在为 Student
class 设置原型时,因为这是错误的。但不知何故这段代码不起作用。有什么帮助吗?
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();
您可以将 getCollegeName
设置为 Person()
调用的 属性,return 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();