例如,在这段代码中
var o = {
set a(value) {this.b = value},
get a() {return this.b}
}
是否可以获取对该 setter 函数的引用o.a
这样如果引用被分配给f
那么我可以做f.call(other, value)
把它用在另一个物体上?
给定您的示例对象:
var o = {
set a(value) {this.b = value},
get a() {return this.b}
}
您可以像这样使用 Object.getOwnPropertyDescriptor :
var setter = Object.getOwnPropertyDescriptor(o, "a").set;
var getter = Object.getOwnPropertyDescriptor(o, "a").get;
var other = {};
setter.call(other, 123);
最后一条语句将在对象“other”上设置值 123。它不影响对象“o”的值。
您还可以使用 getter 从其他地方获取值。
var result = getter.call(other);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)