Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it possible to store a function of the prototype inside a variable?

Tags:

javascript

To improve my understanding of JavaScript, I started to read other people's source code. On Github, I encountered a script that has this variable declaration at the top:

var has = Object.prototype.hasOwnProperty;

Later in the code it's used like this:

if (has.call(params, key)) {  
    // stuff
}

How does this even work? Effectively, has is now some kind of alias for Object.prototype.hasOwnProperty, but why is it possible to store a prototype method in a variable – since it's now a function call, there isn't anything returned.

like image 953
Sven Avatar asked Feb 09 '23 04:02

Sven


1 Answers

A function is a first class citizen in Javascript (as is the case in some other languages as well) that means they can be assigned to variables, passed as arguments to other functions as well as returned from functions. There's a good piece on first class functions on Wikipedia: https://en.wikipedia.org/wiki/First-class_function

like image 63
Lazarus Avatar answered Feb 11 '23 23:02

Lazarus