-2

I have this habit of using function id(_id) { return document.getElementById(_id); } as to lessen the work of typing this over and over.

sidenote:

jquery becomes too heavy for small tasks and projects

As I learnt Javascript more I came to know that we can pass around functions just like objects so we can do

var id = document.getElementById;

It seems like both do the exact same thing. However, I am not an expert in Javascript, so could there be any difference internally? and which is the preferred way of using?

GauravP
  • 61
  • 1
  • 10

1 Answers1

1

Yes, the context is:

const log = console.log;

log("test");

The upper wont work because the context changed, and log must be called on a console object, not on window ( aka without context). However, there are easy workarounds:

const log = console.log.bind(console);

Or you use functions, for example the arrow ones:

const log = (...args) => console.log(...args);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151