How to “override” a defined (get-)property on a prototype?

前端 未结 3 555
北荒
北荒 2020-12-31 01:58

I have some code which defines a getter (but no setter, if such is relevant) on a prototype. The value returned is correct in 99.99% of the cases; however, the goal is to se

3条回答
  •  Happy的楠姐
    2020-12-31 02:37

    By using Object.defineProperty on x:

    var foo = {}
    Object.defineProperty(foo, "bar", {
        // only returns odd die sides
        get: function () { return (Math.random() * 6) | 1; }
    });
    
    var x = Object.create(foo);
    display(x.bar);      // E.g. 5
    
    (function() {
      var bar;
      var proto = Object.getPrototypeOf(x); // Or just use foo
    
      Object.defineProperty(x, "bar", {
        get: function () { return typeof bar !== "undefined" ? bar : proto.bar; },
        set: function(value) { bar = value; }
      });
    })();
    
    display(x.bar);  // Still odd
    x.bar = 4;       // By fair dice roll
    display(x.bar);  // Shows 4
    
    function display(msg) {
      document.body.insertAdjacentHTML("beforeend", "

    " + msg + "

    "); }

    I am looking for if there is a way to stop the behavior of a property in the [prototype] and turn "bar" back into a normal/ad-hoc property.

    Okay, that's slightly different, but still uses Object.defineProperty:

    var foo = {}
    Object.defineProperty(foo, "bar", {
        // only returns odd die sides
        get: function () { return (Math.random() * 6) | 1; }
    });
    
    var x = Object.create(foo);
    display(x.bar);      // E.g. 5
    
    Object.defineProperty(x, "bar", {
      value: undefined,
      writable: true,
      enumerable: true // Or leave off if you want it non-enumerable
    });
    
    display(x.bar);  // undefined
    x.bar = 4;       // By fair dice roll
    display(x.bar);  // Shows 4
    
    function display(msg) {
      document.body.insertAdjacentHTML("beforeend", "

    " + msg + "

    "); }

提交回复
热议问题