为什么我的构造函数不继承超级构造函数的方法?

时间:2017-09-20 04:28:39

标签: javascript node.js inheritance constructor prototype

这是我的第一个问题,所以我可能没有正确地做事。我正在尝试学习JS和Node JS。我正在努力使用util.inherits函数。

即使我使用了util.inherits函数,我也无法理解为什么Human构造函数的属性和方法对于Male的实例是不可用的。 james instance of Human回归正确,因此james对象应该可以访问Human方法。

我知道现在不鼓励util.inherits使用,但想要理解为什么它不能促进我的理解。

var util = require('util');

function Human (){
    this.firstName = 'James';
    this.secondName = 'Michael';
    this.age = 8;
    this.humanFunction = function(){
        console.log('I am a human');
    }
}

function Male (){
    this.gender = 'male';
    this.power = 5;
    this.who = function(){
        return 'I am Male';
    };
}

util.inherits(Male, Human)

let james = new Male();

console.log(james instanceof Human); //true
console.log(james.firstName); //undefined
james.humanFunction(); //james.humanFunction is not a function

2 个答案:

答案 0 :(得分:1)

2017年,以及Node.js tells you not to use this。相反,使用真正的类符号:

// our initial class
class Human {
  constructor(first, second, age) {
    this.firstName = first;
    this.secondName = second;
    this.age = age;
    this.gender = 'unspecified'
  }

  sayWhat() {
    console.log(`I am a human, and my gender is ${this.gender}`);
  }
}

// our 'Male' class, a subclass of Human:
class Male extends Human {
  constructor(first, second, age) {
    super(first, second, age)
    this.gender = 'male';
  }
}

然后我们调用相同的代码,但是使用字符串模板,因为这是现代版本的Node所做的事情:

let james = new Male('james', 'michael', 8);
console.log(`is james a human?: ${james instanceof Human}`);
console.log(`james's first name is: ${james.firstName}`);
console.log(`james says: ${james.sayWhat()}`);

答案 1 :(得分:1)

请添加Human.call(this);在Male()函数中

var util = require('util');

function Human (){
    this.firstName = 'James';
    this.secondName = 'Michael';
    this.age = 8;
    this.humanFunction = function(){
        console.log('I am a human');
    }
}

function Male (){
    this.gender = 'male';
    this.power = 5;
    this.who = function(){
        return 'I am Male';
    };
    Human.call(this);
}

util.inherits(Male, Human)

let james = new Male();

console.log(james instanceof Human); //true
console.log(james.firstName); //undefined
james.humanFunction(); //james.humanFunction is not a function