2
let obj = {};
Object.defineProperty(obj, 'src', {get: () => 'hello'});
Object.defineProperty(obj, 'alias1', {get: () => this['src']});
Object.defineProperty(obj, 'alias2', {get: this['src']});
console.log(obj.src);
console.log(obj.alias1);
console.log(obj.alias2);

outputs:

hello
undefined
undefined

What am I doing wrong?

Poma
  • 8,118
  • 16
  • 59
  • 137
  • 1
    `this` in arrow function is not what you think it is, use regular function expression instead. Reading [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is always helpful. – Teemu Jun 07 '18 at 16:44
  • 1
    Possible duplicate of [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions), or [a wider explanation](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch). – Teemu Jun 07 '18 at 17:02
  • 1
    `Object.defineProperty(obj, 'alias1', {get() { return this['src']}});` – Felix Kling Jun 07 '18 at 21:53
  • Keep in mind that in V8, [own property accessors are about 14x slower than property accessors in `__proto__`](https://stackoverflow.com/q/48893360/1541563). – Patrick Roberts Jun 07 '18 at 21:59

2 Answers2

2

Arrow functions don't bind the same this that you're expecting. In your cases, this refers to the global object. You can test this easily by changing your second line to:

Object.defineProperty(obj, 'alias1', { get: () => { console.log(this) } });  // ==> Window

You'll need to change it to something like these:

Object.defineProperty(obj, 'alias1', { get: () => obj.src });
Object.defineProperty(obj, 'alias2', { get: function () { return this.src } });

Live Example:

let obj = {};
Object.defineProperty(obj, 'src', {get: () => 'hello'});
Object.defineProperty(obj, 'alias1', {get: () => obj['src']});
Object.defineProperty(obj, 'alias2', {get: function () { return this.src }});
console.log(obj.src);
console.log(obj.alias1);
console.log(obj.alias2);
skyline3000
  • 6,896
  • 1
  • 20
  • 32
0
 this['src']

must be

obj["src"]

or even

this.obj["src"]

As the context inside an arrow function is the one it was declared in (window in this case) not the object it is part of.

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120