call function code example

Example 1: running a function in a function javascript

function runFunction() {
  myFunction();
}

function myFunction() {
  alert("runFunction made me run");
}

runFunction();

Example 2: javascript function call with variable

function abc() {
  alert('test');
}

var funcName = 'abc';

window[funcName]();

Example 3: function calls

const obj = {
  foo: 1,
  get bar() {
    return 2;
  }
};

let copy = Object.assign({}, obj); 
console.log(copy); 
// { foo: 1, bar: 2 }
// The value of copy.bar is obj.bar's getter's return value.

// This is an assign function that copies full descriptors
function completeAssign(target, ...sources) {
  sources.forEach(source => {
    let descriptors = Object.keys(source).reduce((descriptors, key) => {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {});
    
    // By default, Object.assign copies enumerable Symbols, too
    Object.getOwnPropertySymbols(source).forEach(sym => {
      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
      if (descriptor.enumerable) {
        descriptors[sym] = descriptor;
      }
    });
    Object.defineProperties(target, descriptors);
  });
  return target;
}

copy = completeAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }

Example 4: call function javascript

// Define your function
function sayHello(msg){
	console.log("Hello, " + msg);
}

// Call it
sayHello("Norris");

// outputs:
// Hello, Norris

Example 5: js call and apply

func.call([thisArg[, arg1, arg2, ...argN]])