如何在JS中定义属性别名?(复制)

时间:2021-10-23 12:36:33

This question already has an answer here:

这个问题已经有了答案:

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?

我做错了什么?

2 个解决方案

#1


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);

#2


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.

由于箭头函数中的上下文是它在(本例中为窗口)中声明的上下文,而不是它所包含的对象。

#1


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);

#2


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.

由于箭头函数中的上下文是它在(本例中为窗口)中声明的上下文,而不是它所包含的对象。