1

I have code is below, I want my result is "Hello Mr. John Doe".

function formatname(name) {
    return name.fullName;
};

const name = {
    firstName: 'John',
    lastName: 'Doe',
    fullName: function() {
        return this.firstName + ' ' + this.lastName;
    }
};

const getName = (
    <h1>Hello Mr. {formatname(name)}</h1>
);

ReactDOM.render(
    getName,
    document.getElementById('root')
);

But when I save it return is "Hello Mr. ", what I wrong in variable fullName.

1 Answer 1

2

In your code:

const name = {
    firstName: 'John',
    lastName: 'Doe',
    fullName: function() {
        return this.firstName + ' ' + this.lastName;
    }
};

this is not refered to your variable name anymore. To solve, you need to bind this back to the name you declared:

formatname(name).bind(name)()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks , It working. Could you tel me ".blind(name)() what does it mean ?
Refer: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.