0

this my code:

obj={
  obj1:{
    funcTest1a:function(){ console.log ("test _1a: ",this)},// this return obj1
    funcTest1b:()=>console.log("test _1b: "+ this), // this return windows
    obj2:{
      funcTest2a:function(){ console.log ("test _2a: ",this)},// this return obj1
      funcTest2b:()=>console.log("test _2b: "+ this), // this return windows
    },
    obj3:{
      test3(){
        console.log(this); 
        obj.obj1.obj2.funcTest2b()
      },          
    }
  }
}

I understand that if I call in the console :

obj.obj1.obj2.funcTest2b()

return window that is ok

but

If I call

obj.obj1.obj3.test3()

inside this function test3() I call

obj.obj1.obj2.funcTest2b()

in which case I expected "THIS" to be different.

a possible return from an arrow function a this that is not window or global?

> I find a solution o better an answer

this is an example of how to use arrow function where THIS is not a global

a = {
    hello: 'hola',
    b() {
        return () => {
            console.log(this.hello) //or this;
        }
    }
}

a.b()() // print hola

so in my code, I have to change:

funcTest2b:()=>console.log("test _2b: "+ this) in

funcTest2b: function(){
        let testInside=()=>console.log("test _2b: "+ this)
        testInside()
       }
Angelotti
  • 307
  • 2
  • 15
  • An arrow function's `this` is inherited from the outer scope (*not* from the function caller) – CertainPerformance Sep 09 '19 at 08:28
  • You cannot use `this` or `arguments` inside arrow functions, they will point to the surrounding scope. – nick zoum Sep 09 '19 at 08:29
  • is also no possible to bind an arrow function right? – Angelotti Sep 09 '19 at 08:38
  • @Angelotti no, it's not. [Arrow functions have a fixed context](https://stackoverflow.com/questions/33308121/can-you-bind-arrow-functions) determined at the time of their creation. – VLAZ Sep 09 '19 at 08:51
  • @VLAZ yes ok.... but I create funcTest2b inside obj2 and I call in Obj3... why I still have window? it's possible to give a "this" in arrow function another value than global? is possible only using this as a parameter? – Angelotti Sep 09 '19 at 09:12
  • @Angelotti but *at the time of creating them*, the lexical context [isn't the object that is currently being created by the object literal](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers). The `this` context would be the context *where the object literal is*. I suggest reading through the dupes because the `this` keyword doesn't work the way you think it does - it *only* references the current context which can vary by the way the code is executed. It doesn't reference "the current object instance" as with other languages. – VLAZ Sep 09 '19 at 10:36
  • Ok just in order to understand....how can I use arrow function in order to have another "THIS" that is not window or Global????? some examples??? – Angelotti Sep 09 '19 at 11:45

0 Answers0