rster
rster

Reputation: 5

Javascript setter - How to get the name of the setter inside of the setter?

So I need to get the name of the setter that is called when I assign a value to it. Like this:

var b = {};

var a = {
 set hey(value) {
  b[<name of setter>] = value;
 }
}

I want the name of setter to be 'hey', so b.hey equals the value you set a.hey to.

I've been searching for a couple of days now and can't find an answer to my problem. Help would be much appreciated!

Upvotes: 0

Views: 62

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370859

You can check arguments.callee.name to get the function name, slice off the leading set, and assign it to a property of b:

var b = {};
var a = {
  set hey(value) {
    const name = arguments.callee.name.slice(4);
    b[name] = value;
  }
}
a.hey = 'foo';

console.log(b);

This will fail in strict mode, though - you might consider using a Proxy instead for a, if possible:

var b = {};
var a = new Proxy({}, { set: (_, prop, val) => {
  b[prop] = val;
}});
a.hey = 'foo';

console.log(b);

Upvotes: 1

Related Questions