最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to get a reference to the setter function of a "setter"? - Stack Overflow

programmeradmin0浏览0评论

For example, in this code

var o = {
  set a(value) {this.b = value},
  get a() {return this.b}
}

is it possible to get a reference to that setter function for o.a so that if the reference is assign to f then I can do f.call(other, value) to use it on another object?

For example, in this code

var o = {
  set a(value) {this.b = value},
  get a() {return this.b}
}

is it possible to get a reference to that setter function for o.a so that if the reference is assign to f then I can do f.call(other, value) to use it on another object?

Share Improve this question asked Feb 9, 2015 at 3:14 trusktrtrusktr 45.5k58 gold badges209 silver badges287 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 19

Given your example object:

var o = {
    set a(value) {this.b = value},
    get a() {return this.b}
}

You can use Object.getOwnPropertyDescriptor like this:

var setter = Object.getOwnPropertyDescriptor(o, "a").set;
var getter = Object.getOwnPropertyDescriptor(o, "a").get;

var other = {};
setter.call(other, 123);

That last statement will set the value 123 on object "other". It does not affect the value on the object "o".

You can also get the value from other using the getter.

var result = getter.call(other);

Try Object.getOwnPropertyDescriptor. It will return an object with getter and setter methods.

发布评论

评论列表(0)

  1. 暂无评论