Javascript为什么实例化不是instanceof声明的类?

时间:2016-01-01 06:48:14

标签: javascript

我创建了一个人类。当我将其实例化为daffyDuck实例时,它不会被识别为A_person的实例。为什么不呢?

var A_person = function(firstAndLast) {
  var splitName = firstAndLast.split(" ");
  return {
    getFullName: function(){
      return splitName.join(" ");
    } 
  };
};

var daffyDuck = new A_person('Daffy Duck');
daffyDuck instanceof A_person  // false (I expected this to be true!)

3 个答案:

答案 0 :(得分:2)

我认为您打算使用原型而不是一个构造函数(返回一个对象)......这样的事情

function A_Person(firstAndLast){
    this.splitName = firstAndLast.split(" ");
}
A_Person.prototype.getFullName = function(){
     return splitName.join(" ");
}

有关详细信息,请参阅此处https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

答案 1 :(得分:1)

你根本没有定义一个班级。您只是创建一个方法并将其保存到变量。

您需要实际定义类。从ES6开始,这非常简单 - (learn more here):

class A_person {
  constructor(firstAndLast) {
    var names = firstAndLast.split(" ");
    this.firstName = names[0];
    this.lastName = names[1];
  }
}

var daffyDuck = new A_person('Daffy Duck');

答案 2 :(得分:1)

您可以删除return语句并改为使用this将该函数附加到对象。

var A_person = function(firstAndLast) {
  var splitName = firstAndLast.split(" ");
  this.getFullName = function(){
      return splitName.join(" ");
    } 
};

var daffyDuck = new A_person('Daffy Duck');
daffyDuck instanceof A_person  // true
相关问题