Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 具有Object.defineProperty的getter是否可以访问该实例?_Javascript_Ecmascript 6_This_Defineproperty - Fatal编程技术网

Javascript 具有Object.defineProperty的getter是否可以访问该实例?

Javascript 具有Object.defineProperty的getter是否可以访问该实例?,javascript,ecmascript-6,this,defineproperty,Javascript,Ecmascript 6,This,Defineproperty,假设有一个人: const Person = function(fname, lname) { this.fname = fname; this.lname = lname; }; 我想用一个“name”getter扩展它的功能 然而,这是行不通的。getter中的this不是调用它的实例原型: const p = new Person('Taylor', 'Swift'); p.name // "undefined undefined" 而是财产定义的范围: fname =

假设有一个人:

const Person = function(fname, lname) {
    this.fname = fname;
    this.lname = lname;
};
我想用一个“name”getter扩展它的功能

然而,这是行不通的。getter中的
this
不是调用它的实例原型:

const p = new Person('Taylor', 'Swift');
p.name // "undefined undefined"
而是财产定义的范围:

fname = 'Someone';
lname = 'Else';
p.name // "Someone Else"

在写这个问题的过程中,答案是显而易见的。仍然张贴,以防它帮助其他人

Getter属性确实绑定到它们的宿主对象

问题是我对getter使用了arrow函数。箭头函数没有自己的
this
,而是使用封闭执行上下文的
this

这意味着为getter属性执行的
bind
ing没有效果

例如:

const foo = () => this.document;
foo() // global document object
foo.call({document: 'na'}) // still global document object
const bar = foo.bind({document: 'na'});
bar(); // still global document object
const foo = () => this.document;
foo() // global document object
foo.call({document: 'na'}) // still global document object
const bar = foo.bind({document: 'na'});
bar(); // still global document object