getOwnPropertyDescriptor在有值时返回undefined

时间:2014-01-30 15:37:14

标签: javascript oop

我一直想用getOwnProperty一小时尝试解决返回undefined,我查看我的笔记并找不到原因,可以请一些检查甚至更好地解释一下为什么这个行为???这里的主要目标是覆盖扩展另一个方法的属性。

以下是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);

1 个答案:

答案 0 :(得分:6)

您获得undefined的原因是employee变量没有名为fullName的“自有”属性。该属性属于Person.prototype

尝试一下:

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

如果您更改该行,则其余代码应按原样运行。

供参考(强调添加):

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

  

Object.getOwnPropertyDescriptor()方法为自己的属性返回一个属性描述符( ,即一个直接存在于对象上的属性描述符,不存在于对象的原型链中 )给定对象。