October 22, 2024
Chicago 12, Melborne City, USA
javascript

Sending parameters via function.call()


Wondering how to make this work.

A particular IP address is associated with a particular function. (Note: In this example, I am using short people names instead of IP addresses, but the idea is the same.)

How can I pass the keyname(*) to the called function?

const $ = document.querySelector.bind(document);
const obj = {bob:sayname, ann:sayname, ed:sayhi};

$('input').addEventListener('keyup', readme);
function readme(e){
    console.log(e.target.value);
    if ( e.target.value in obj){
    console.log('got here...');
    obj[e.target.value].call(e.target.value); //<== I want to do THIS
    obj[e.target.value].call('Fred'); //<== but this doesn't work either
  }
}
function sayname(usr){
    console.log(usr);
    console.log('Name: ', usr);
}
function sayhi(usr){
    console.log(usr);
    alert('hi, ' + usr);
}
<input type="text">

(*) Which would be the IP address (being passed to the function) — or, in this example, the human name (Bob, Ann, Ed). Basically, in the func I wish to use that IP address, so I need to pass it into the func.

UPDATE:

  1. Here is a fiddle to play with: https://jsfiddle.net/8k0fmhdg/

  2. The reason for using .call() is to be able to pass parameters to the function. If there is another / better way to do this, please enlighten me. I thought I’d tried every permutation/combination, but I am sure I missed one or two — and probably the most obvious one… (That’s just how I roll…)



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video