confusing bind. how to bind an object to another? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of confusing bind. how to bind an object to another? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

in this code,

var person = {
  first: 'person',
  last: 'sdfsd',
  full: function fullName() {return this.first +  ' ' + this.last;}
}

var john = {
    first:  'person',
    last : 'sdfsd'
}

how do I bind john to person such that something like

var Name = john.bind(person)

can call:

Name.full();

tried couple of things and getting: this.full is not a function OR Name.full is not a function;

I also want to understand whether bind can be used on objects like above or the object has to be a function object to use bind upon?

UPDATE

When I do this:

var person = {
  first: 'person',
  last: 'sdfsd',
  full: function fullName() {console.log(this.first +  ' ' + this.last);}
}

var john = {
    first:  'john',
    last : 'sdfsd',
  fl: function() {return this.full();}
}

var Name = person.full.bind(john);

Name();

I get

john sdfsd

So I infer:

  • bind works only on functions. Is that correct?
  • I thought that if I bind like var Name = john.fl.bind(person); then this would be, upon calling Name();, person and call console.log(person.first + ' ' + person.last); but instead I had to swap the 2 to get the right output. Could someone tell me what gets bound to what? in x.bind(y)??

UPDATE 2 A little bit of .bind function that Ive understood:

If I create something like this:

var jane = function (first, last) {
  if (first) {this.first = first;}
  if (last) {this.last = last;}
  return this.full();
}

And bind it to person fellow above:

var janeName = jane.bind(person);
janeName();

I get:

person sdfsd

in the console. However, the root of my problem was to get the first and last vars defined in Jane, if I would optionally:

janeName.call(jane, 'jane', 'austen');

this returns:

jane austen

Correct me if I am wrong. How this works is janeName is as usual, jane, but the this is bound to Person. BUT, calling with .call janeName is jane bound to person with optional args provided, here actually jane calls itself, with optional args provided, but in turn is bound to person as well, when looking up for .full function.

Answer

Simple:

john.full = person.full;
var name = john.full();

The bind way would look like this:

var name = person.full.call(john);  // call the full() function using john as context

var getName = person.full.bind(john);  // create a function to get the full name from john
var name = getName();
We are here to answer your question about confusing bind. how to bind an object to another? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji