black_yurizan black_yurizan - 3 months ago 5
Javascript Question

Can someone explain to me why the binding method doesn't work in these examples

In this example, when I add the bind method to the end of the function called deeper. the binding method doesn't work.

var body = document.body;

function Depth() {

this.state = "I am inside here";

this.deep = function() {

function deeper() {

body.innerHTML = this.state;
}.bind(this);

deeper();
}

}


var obj = new Depth();

obj.deep();


And in this example, when I add the bind method to the end of the new object that is calling the deep method. The binding method doesn't work.

var body = document.body;

function Depth() {

this.state = "I am inside here";

this.deep = function() {

function deeper() {

body.innerHTML = this.state;
}

deeper();
}

}


var obj = new Depth();

obj.deep().bind(this);


I already know what to do to make the function run properly and to print out the this.state code. But, I want some explanation as to why the first two examples do not work because those were the first ideas I had to write the code in. Here is the last example that worked properly.

var body = document.body;

function Depth() {

this.state = "I am inside here";

this.deep = function() {
var state = this.state

function deeper() {

body.innerHTML = state;
}

deeper();
}

}


var obj = new Depth();

obj.deep();

Answer

'Function.prototype.bind()' returns a new method without changing the original method, so you have to assign the new method to a variable, and then you can use it:

    var deeper = function deeper() {

        body.innerHTML = this.state;
    }.bind(this);


    obj.deep = obj.deep.bind(this); // you can bind an object method, and then reassign it to the original property
Comments