GetOwnPropertyDescriptor returns undefine when it matters

I tried to solve getOwnProperty undefined for one hour, I check my notes and cannot find the reason, I might like to check some1 or even better explain to me why this behavior ??? The main goal here is simply to rewrite the property to a method that extends another one.

Here is jsfiddle

var Person = function(firstName, lastName) {
 this.firstName = firstName;
 this.lastName = lastName;
};

Object.defineProperties(Person.prototype, {
  sayHi : {
    value : function() {
     return "Hi there";
    },
    writable: true,
    enumerable : true
  },

  fullName : {
    get : function() {
     return this.firstName + " " + this.lastName;
    },
    configurable : true,
    enumerable : true
  }

 });

 var createEmployee = function(firstName, lastName, ocupation) {

    var employee = new Person(firstName, lastName);
    employee.ocupation = ocupation;

    /*over-w sayHi*/

    var sayHifn = employee.sayHi.bind(employee);

    employee.sayHi = function() {
      return sayHifn() + " my name is " + this.firstName;
    };

    /*over-w fullName*/

    var fullName = Object.getOwnPropertyDescriptor(employee, "fullName");
    var fullNameFn = fullName.get.bind(employee);

    Object.defineProperty(employee, 'fullName', {
     get : function() {
      return fullNameFn() + " this is o-w ";
     }

    });

    return employee;

  };

  var record = createEmployee('jhon', 'doe', 'eng');
  console.log(record);
+3
source share
1 answer

The reason you get undefinedit is because the variable employeedoes not have its own property called fullName. This property belongs to Person.prototype.

Try:

var fullName = Object.getOwnPropertyDescriptor(Person.prototype, "fullName");

If you change this line, the rest of your code should work as is.

Link (highlighted by me):

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor

Object.getOwnPropertyDescriptor() (, , -) .

+5

All Articles