我能知道通用 getter/setter 在其主体中应用什么属性吗?
上下文 (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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getters 不是这样工作的。对象的属性可以具有
value
或get
函数。如果该属性有一个值
,则读取该属性:返回该
值
。但是,如果某个属性具有get
函数,则读取该属性会触发该函数。因此,如果必须动态计算某个属性的值,或者想要在读取该属性时执行某些操作,则可以使用 getter。例如,
.innerHTML
需要一个 getter,因为它的值不是静态存储的,而是在访问时计算:在这里,浏览器必须序列化
div 元素。
因此,如果您想要一个 .get() 函数来检索各种属性(Backbone.js 有这样的函数),那么您就不需要寻找 getter。
您想要的最简单的实现是:
That's not how getters work. A property of an object can either have a
value
or aget
function. If the property has avalue
, then reading the property:returns that
value
. However, if a property has aget
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: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: