为什么bob instanceof Person返回false?

时间:2016-06-10 23:31:34

标签: javascript class

我需要有人向我解释为什么bob instanceof Person会从此代码返回false:

var Person = function(firstAndLast) {

    var names = firstAndLast.split(' ');

    return {

        getFirstName:  function() {
          return names[0];
        },

        getLastName: function() {
          return names[1];
        },

        getFullName: function() {
          return names[0] + " " + names[1];
        },

        setFirstName: function(first) {
          names[0] = first;
        },

        setLastName: function(last) {
          names[1] = last;
        },

        setFullName: function(firstAndLast) {
          names = firstAndLast.split(' ');
        }

    };  

};

var bob = new Person('Bob Ross');

我试过寻找答案,但我找不到任何答案。据我所知bob instanceof Person应该返回true,但它没有。

1 个答案:

答案 0 :(得分:2)

问题是你从构造函数返回一个对象。该对象不是new初始化的对象,因此它不是Person类的实例。您应该在构造函数中分配this.propertyname,并让它返回其默认值。



var Person = function(firstAndLast) {

  var names = firstAndLast.split(' ');


  this.getFirstName = function() {
    return names[0];
  };

  this.getLastName = function() {
    return names[1];
  };

  this.getFullName = function() {
    return names[0] + " " + names[1];
  };

  this.setFirstName = function(first) {
    names[0] = first;
  };

  this.setLastName = function(last) {
    names[1] = last;
  };

  this.setFullName = function(firstAndLast) {
    names = firstAndLast.split(' ');
  };

};

var bob = new Person('Bob Ross');

console.log(bob instanceof Person);