iksose iksose - 2 months ago 9
Javascript Question

JavaScript properties with setter methods aren't real properties?

function Name(first, last) {
this.first = first;
this.last = last;
this.fullName = first + " " + last
}

Name.prototype = {
get fullName() {
return this.first + " " + this.last;
},

set fullName(name) {
var names = name.split(" ");
this.first = names[0];
this.last = names[1];
}
};

var person = new Name("Foo", "Bar");
// person.fullName = "Foo Bar"
person.hasOwnProperty("fullName") // false


Is there a way to return the properties?

Answer

As InvernoMuto points out, Object.hasOwnProperty("fullName") returns false because it is not person's own property; it is inherited via the prototype chain. When you use this.fullName = "..."; in your constructor, you are invoking the inherited setter, not adding a new property.

If you want to find such properties, you can:

  1. Use a for..in loop:
for (var prop in person) {
    // this will iterate over EVERY property in person's prototype chain
}
  1. Attach the properties in your constructor:

function Name(first, last) {
  this.first = first;
  this.last = last;

  Object.defineProperty(this, "fullName", {
    get: function() {
      return this.first + " " + this.last;
    },
    set: function(name) {
      var names = name.split(" ");
      this.first = names[0];
      this.last = names[1];
    }
  });
}

var person = new Name("Ronald", "McDonald");
console.log(person.hasOwnProperty("fullName")); // true

  1. Create a whole new object in your constructor, using the get/set syntax that you have there. In this case, we wouldn't use the new keyword but just call the function:

function Name(first, last) {
    return {
        first: first,
        last: last, 

        get fullName() { return this.first + " " + this.last; },
        set fullName(name) { 
            var names = name.split(" ");
            this.first = names[0];
            this.last = names[1];
        }
    };
};

var person = Name("Ronald", "McDonald");
console.log(person.hasOwnProperty("fullName")); // true

Comments