我能知道通用 getter/setter 在其主体中应用什么属性吗?

发布于 2025-01-05 19:53:53 字数 359 浏览 0 评论 0原文

上下文 (this) 自然是请求属性的对象,但没有参数传递给 getter 函数。我希望能够在不使用闭包的情况下获取所请求的属性的名称,但看起来这是唯一的方法。

Object.defineProperty( someObj, "prop1", { get: genericGetter } );
Object.defineProperty( someObj, "prop2", { get: genericGetter } );

function genericGetter() {
    // i want to figure out whether this is called on prop1 or prop2
}

The context (this) is naturally the object that the property is being requested on, but there are no arguments passed to the getter function. I'd like to be able to get the name of the property being requested without using closures but it's looking like that's the only way to do it.

Object.defineProperty( someObj, "prop1", { get: genericGetter } );
Object.defineProperty( someObj, "prop2", { get: genericGetter } );

function genericGetter() {
    // i want to figure out whether this is called on prop1 or prop2
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轻拂→两袖风尘 2025-01-12 19:53:53

我可以告诉我通用 getter/setter 在其应用程序中应用什么属性吗?
身体?

getters 不是这样工作的。对象的属性可以具有 valueget 函数。如果该属性有一个,则读取该属性:

var x = obj.prop;

返回该。但是,如果某个属性具有 get 函数,则读取该属性会触发该函数。因此,如果必须动态计算某个属性的值,或者想要在读取该属性时执行某些操作,则可以使用 getter。

例如,.innerHTML 需要一个 getter,因为它的值不是静态存储的,而是在访问时计算:

var html = div.innerHTML;

在这里,浏览器必须序列化 div 元素。

因此,如果您想要一个 .get() 函数来检索各种属性(Backbone.js 有这样的函数),那么您就不需要寻找 getter。

您想要的最简单的实现是:

someObj.getProp = function ( name ) {
    // perform required tasks
    return this[ name ];
};

Can I tell what property a generic getter/setter applies to in its
body?

That's not how getters work. A property of an object can either have a value or a get function. If the property has a value, then reading the property:

var x = obj.prop;

returns that value. However, if a property has a get function instead, then reading that property triggers that function. So, you use getters if the value of a certain property has to be computed dynamically, or if you want to perform certain operations whenever the property is read.

For instance, .innerHTML requires a getter, because its value is not stored statically, but computed on access:

var html = div.innerHTML;

Here, the browser has to serialize the DOM structure that is contained within the div element.

So, if you want a .get() function that retrieves various properties (Backbone.js has such a function), then you're not looking for getters.

The simplest implementation of what you want would be:

someObj.getProp = function ( name ) {
    // perform required tasks
    return this[ name ];
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文