How to "override" a specific property (get-) on a prototype?

I have code that defines a getter (but no prototype, if any) on the prototype. The return value is true in 99.99% of cases; however, the goal is to set the property to be evaluated to a different value for a particular object.

foo = {} Object.defineProperty(foo, "bar", { // only returns odd die sides get: function () { return (Math.random() * 6) | 1; } }); x = Object.create(foo); x.bar // => eg. 5 x.bar = 4 // by fair dice roll x.bar // nope => eg. 3 

How to override a property for x, an existing object, so that it can be assigned (for example, has a property property by default)?

Addition. Although a new property (value or get / set) can be defined in x, I am looking for if there is a way to stop the behavior of the property in [prototype] and include "bar" back in normal / ad-hoc for a specific instance.

+6
source share
1 answer

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); // Eg 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", "<p>" + msg + "</p>"); } 

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

Ok, this is a little 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); // Eg 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", "<p>" + msg + "</p>"); } 
+6
source

Source: https://habr.com/ru/post/1204404/


All Articles