-1

I'm just playing around and trying to figure out how the this object works and how do I pass scopes context with the bind function.
So far I got to this point (check code below), and found out that I can use bind with an object function in order to pass the scope of myObject to the object function run.

first question:

why do I need to use this.first() instead of first()?

Because otherwise its still using second's context.

    myObject = {
    first: function(){ console.log("myObject's first()")},
    second: function(){ 
        function first(){ console.log("second's first()")};
        let run = function(){ this.first()}.bind(this);
        run();

    },
}

myObject.second()

Next, I wanted to take it to the next level and I nested another function within second (check code). Second question:

From the code below i get the error Error: this.first is not a function, and whether i invoke .bind(this) or not it gives the same error, any clue why does this happen?

myObject = {
    first: function(){ console.log("myObject's first()")},
    second: function(){ 
        function first(){ console.log("second's first()")};
        function secondx2(){
            function first(){ console.log("secondx2's first()")};
            let run = function(){ this.first()}
            run();
        }
        secondx2();
    },
}

myObject.second()
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
user3676224
  • 793
  • 2
  • 9
  • 22
  • `this` and variable scope are pretty much unrelated. `Function#bind` returns a new function that calls its target function with a specific `this` value, but doesn’t affect scope at all, like `call` and `apply`. – Ry- Feb 07 '18 at 21:47
  • You called `secondx2()` without providing it a `this`. Do `secondx2.call(this);` NB: Consider using arrow functions, the way it uses the *lexical* `this` is probably more suitable for your case. – trincot Feb 07 '18 at 21:51
  • @Ryan ya, but why can't i run this.first() i the second snippet? – user3676224 Feb 07 '18 at 22:14
  • @user3676224: Explained by trincot’s comment and the duplicate. – Ry- Feb 07 '18 at 22:22

1 Answers1

0

Consider using arrows or try to store this in a global variable to access your functions

myObject = {
    first: function(){ console.log("myObject's first()")},
    second: function(){ 
        var scope = this;
        function first(){ console.log("second's first()")};
        function secondx2(){
            function first(){ console.log("secondx2's first()")};
            let run1 = function(){ scope.first()} //myObject's first()

            let run2 = function(){ first()}//secondx2's first()

            run1();
            run2();
        }
        secondx2();
    },
}

myObject.second()
Melchia
  • 16,699
  • 16
  • 70
  • 93