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 callingName();
, person and callconsole.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.