如何“覆盖”原型上定义的(get-)属性? [英] How to "override" a defined (get-)property on a prototype?

查看:146
本文介绍了如何“覆盖”原型上定义的(get-)属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以在原型上定义一个getter(但是没有setter,如果相关的话)。返回的值在99.99%的情况下是正确的;但是,目标是将属性设置为评估特定对象的不同值。

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 set the property to evaluate to a different value for a specific 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

如何为x(现有对象)覆盖属性,使其成为可分配(例如,有默认属性行为)?

How can the property be overridden for x, an existing object, such that it is assignable (eg. has default property behavior)?

附录:虽然可以在x上定义新属性(值或获取/设置),但我正在寻找如果有一种方法可以停止 [原型]中属性的行为,并将bar变回特定实例的普通/ ad-hoc属性。

Addendum: While a new property (value or get/set) can defined on x, 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 for the specific instance.

推荐答案

x Object.defineProperty c>:

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


我正在寻找是否有办法停止房产的行为[原型]并将bar变回普通/ ad-hoc属性。

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.

好的,这略有不同,但仍然使用 Object.defineProperty

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

这篇关于如何“覆盖”原型上定义的(get-)属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆