[英]JavaScript “this” keyword and arrow function
Here this keyword which is in arrow function points to obj 's variable environment这里箭头 function 中的这个关键字指向obj的变量环境
var greeting = 'hi'; const obj = { greeting: 'hey', fo() { const greeting = 'hola'; const arrowFo = () => { console.log(this.greeting); }; arrowFo(); }, }; obj.fo(); //logs: hey
var greeting = 'hi'; const obj = { greeting: 'hey', fo() { const greeting = 'hola'; const fo2 = function () { const greeting = 'hello'; const arrowFo = () => { console.log(this.greeting); }; arrowFo(); }; fo2(); }, }; obj.fo(); //logs: hi
Arrow functions have no this value in their scope, so you can access this
value of the object.箭头函数在其 scope 中没有此值,因此您可以访问 object 的
this
值。 But Normal functions have this value in their scope, in this example this
value of the normal function is globalThis or window.但是普通函数在它们的 scope 中有这个值,在这个例子中,普通 function 的
this
值是 globalThis 或 window。 and it allows to you access the global scope.它允许您访问全局 scope。 if you call
fo2
with this
value of object instead of globalThis you get '"hey"'如果你用
this
值 object 而不是 globalThis 调用fo2
你会得到 '"hey"'
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
const fo2 = function () {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
fo2.call(this) // Use this instead of fo2()
},
};
In JavaScript the this object is really based on how you make your function calls.在 JavaScript 中,这个 object 实际上是基于您如何进行 function 调用。 the fo2() function is not binded in any object for this purpos it get the this of global context
fo2() function 未绑定在任何 object 中,为此它获得全局上下文的 this
you have to declare your function with the this like this:你必须像这样声明你的 function :
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
this.fo2 = function () {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
this.fo2();
},
};
obj.fo(); //logs: hi
or use arrow function like this:或像这样使用箭头 function :
var greeting = 'hi';
const obj = {
greeting: 'hey',
fo() {
const greeting = 'hola';
fo2 = () => {
const greeting = 'hello';
const arrowFo = () => {
console.log(this.greeting);
};
arrowFo();
};
fo2();
},
};
obj.fo();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.