1

I have the next task:

const person = {name: 'Arnold'};

function fn(salut, lastName) {
    console.log(salut, this.name, lastName);
}

const bindName = bind(fn, person, 'Mr');

bindName('Helgov');

I have to write a function that prints: "Mr Arnold Helgov"

My realization of this task is the next function:

function bind(fn, person, salute) {
    return (lastname) => {
        return fn(salute, lastname);
    }
}

But I have a problem here. My function prints only "Mr Helgov" and the name 'Arnold' is lost. How to solve this problem (maybe by using bind or apply or call)?

1 Answer 1

2

How to solve this problem (maybe by using bind or apply or call)?

Yes, you can use call or bind to make sure this gets to be equal to person during the call of fn.

With call:

const person = {name: 'Arnold'};

function fn(salut, lastName) {
    console.log(salut, this.name, lastName);
}

const bindName = bind(fn, person, 'Mr');

bindName('Helgov');

function bind(fn, person, salute) {
    return (lastname) => {
        return fn.call(person, salute, lastname);
    }
}

Or, bind:

const person = {name: 'Arnold'};

function fn(salut, lastName) {
    console.log(salut, this.name, lastName);
}

const bindName = bind(fn, person, 'Mr');

bindName('Helgov');

function bind(fn, person, salute) {
    return fn.bind(person, salute);
}

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.