除非设置为可写,否则无法覆盖readyOnly可配置的函数值对象原型属性

时间:2015-07-03 10:07:58

标签: javascript oop inheritance prototype

在下面的代码中,我有2个属性:

  • sharedProperty:它有一个原始类型作为值,并且设置为只可配置。
  • sharedMethodAsProperty:它有一个值作为值,也可以设置为可配置。

现在,在代码片段的末尾,我可以覆盖sharedProperty就好了(readonlyconfigurable),但对于sharedMethodAsProperty,我必须将其设置为writable否则我抱怨readonly财产无法被覆盖。想法?

(function () {
'use strict';
var Person = function () {
  Object.defineProperties(Person.prototype, {
    "sharedProperty" : {
      value : 10,
      configurable: true
    },

    "sharedPropertyThroughAccessor" : {
      get : function() {
        return "shared property";
      },
      configurable: true
    },

    "sharedMethodAsProperty" : {
      value: function() {
      return "shared method as property";
      },
      configurable: true,
      // if we omit this true here, we can't override it below.
      //writable: true
    }
  });
};

Object.prototype.sharedMethod = function() {
  return "shared method";
};

var person1 = new Person("John", "Doe");
var man = Object.create(person1);

var sharedProperty = Object.getOwnPropertyDescriptor(Person.prototype, "sharedProperty").value;
Object.defineProperty(man, "sharedProperty", {
  value : 11 + sharedProperty,
  configurable: true
});

var sharedPropertyThroughAccessor = Object.getOwnPropertyDescriptor(Person.prototype, "sharedPropertyThroughAccessor");
// bind with man, else you'd get person1's properties
var sharedFn = sharedPropertyThroughAccessor.get.bind(man);
Object.defineProperty(man, "sharedPropertyThroughAccessor", {
  get : function() {
    return sharedFn() + " overridden";
  }
});

var sharedMethodFn = person1.sharedMethod.bind(man);
// can't do: man.prototype. That property only exists on functions.
man.sharedMethod = function() {
  return sharedMethodFn() + " overridden";
};

var sharedMethodAsProperty = Object.getOwnPropertyDescriptor(Person.prototype, "sharedMethodAsProperty");
var sharedMethodAsPropertyFn = sharedMethodAsProperty.value.bind(man);
man.sharedMethodAsProperty = function() {
  return sharedMethodAsPropertyFn() + " overridden";
};
}());

1 个答案:

答案 0 :(得分:1)

随着fuyushimoya的帮助,我意识到我是多么愚蠢,为什么它不起作用。

  • sharedProperty已为man对象重新定义,但永远不会为其分配新值,因此即使没有sharedPropertywritable,覆盖也会起作用。
  • sharedMethodAsProperty正在为man对象分配一个新值。正在创建新的function并将其分配给它。分配将要求它为writable。使用Object.defineProperty()重新定义它是有意义的,就像sharedProperty对象覆盖man的方式一样。