How to obtain the values according to their context?

0

I want to get the fullname values 'name1', 'name2', 'name3', according to the context that is found. it would be useful to use the bind, call or apply functions.

var fullname = 'name1';

var person = {
  last: {
    fullname: 'name3',
  },
  fullname: 'name2',
  getFullname: function() {
    return this.fullname
  }
}
 
    
asked by x-rw 07.01.2018 в 04:44
source

3 answers

2

The only difference between the methods, call () , apply () , and bind () is in the invocation.

The call () method calls a function with a value this assigned and arguments provided individually.

person.getFullname.call(); // 'name2'
person.getFullname.call(this); // 'name1'
person.getFullname.call(person); // 'name1'
person.getFullname.call(person.last); // 'name3'
person.getFullname.call({ fullname: 'hola' }); // 'hola'

The apply () method invokes a certain function by assigning explicitly the this object and an array or object such as arguments for that function.

person.getFullname.apply(); // 'name1'
person.getFullname.apply(this); // 'name1'
person.getFullname.apply(person); // 'name2'
person.getFullname.apply(person.last); // 'name3'
person.getFullname.apply({ fullname: 'hola' }); // 'hola'

The bind () method creates a new function, which when it is called, it assigns to its operator this the delivered value, with a sequence of arguments given preceding any delivered when the function is called.

person.getFullname.bind()(); // 'name1'
person.getFullname.bind(this)(); // 'name1'
person.getFullname.bind(person)(); // 'name2'
person.getFullname.bind(person.last)(); // 'name3'
person.getFullname.bind({ fullname: 'hola' })(); // 'hola'
  

Source: link

    
answered by 07.01.2018 / 10:24
source
1

Surely there are more ways to get some value but I think these are the most significant:

// name1
console.log( fullname );

// name2
console.log( person.getFullname() );
console.log( person.fullname );

// name 3
console.log( person.last.fullname );
console.log( person.getFullname.call( person.last ) );
console.log( person.getFullname.apply( person.last ) );

let getName3 = person.getFullname.bind( person.last );
console.log( getName3() );

The functions call , apply and bind can be used to obtain the values using the function getFullname by passing objects that have the same substructure as person , in this case objects that have a property called fullname .

    
answered by 07.01.2018 в 09:05
0

Hi, I do not know if it can help you,

var fullname = 'name1';

var person = {
  last: {
    fullname: 'name3',
  },
  fullname: 'name2',
  getFullname: function() {
    return fullname + " " + this.fullname + " "  +  this.last.fullname
  }
}

console.log(person.getFullname())
    
answered by 07.01.2018 в 05:05