Ad

Javascript Why Is Instantiation Not Instanceof Declared Class?

- 1 answer

I created a person class. When I instantiate it as the daffyDuck instance, it is not recognized as an instance of A_person. Why not?

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!)
Ad

Answer

You can remove the return statement and use this instead, to attach the function to objects.

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
Ad
source: stackoverflow.com
Ad