QriousBen
QriousBen

Reputation: 1

How so I set the 'this' value for a function inside of another function without the using bind()?

Objective: My goal is to call the setUserName method of the clientData object in such a way that the property: fullName is set to the proper values.

What I've Done: I attempted the following code:

getUserInput.call(clientData,"My","Name",clientData.setUserName)

I thought that by doing this, the this value inside of the getUserInput() function would be set to my object clientData which it did. Furthermore, I thought that all code inside of getUserInput(){} would have access to this modified this value. So along that thought process, I figured that the this value accessed by callback() would also be clientData. Unfortunately, the code inside callback() was still accessing a this value of window. I do not understand why.

My workaround was to bind setUserName to clientData. Is there another way to achieve my goal without modifying clientData or getUserInput()?

var clientData = {
    fullName: "Not Set",
    setUserName: function (firstName, lastName) {
      this.fullName = firstName + " " + lastName;
    }
};

function getUserInput(firstName, lastName, callback) {
    callback(firstName, lastName);

    }

getUserInput("My", "Name", clientData.setUserName.bind(clientData));
    console.log (clientData.fullName);
    console.log (window.fullName);

Upvotes: 0

Views: 94

Answers (1)

Jared Smith
Jared Smith

Reputation: 21965

Your code does not actually bind getUserInput. Function.prototype.bind() returns a NEW function with a bound this value and passes that as the callback argument.

Upvotes: 2

Related Questions