如何在不使用new关键字的情况下设置原型函数

时间:2017-02-28 07:19:15

标签: javascript prototypal-inheritance

在原型继承的一个简单示例中,我想将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();

1 个答案:

答案 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();