简体   繁体   中英

Why functions are objects in javascript?

Please, explain to me why functions are objects in javascript? An object is a structure with properties. Value of property may be a function and we call this property - method. But we can NOT execute an object. We can NOT do this:

var cat = {name: 'Murzik', age: 17};
cat();

But we can execute the function

var func = function() {
    alert('Hello world!');
};
func();

So, if functions are objects why we can do this? Please, help me to understand! Thank's!

Because the ECMAScript spec says so:

4.3.24 function

member of the Object type that is an instance of the standard built-in Function constructor and that may be invoked as a subroutine

Note that

  • Some objects are not callable:

     var obj = {}; typeof obj; // "object" --> It's not callable obj(); // TypeError: obj is not a function 
  • Some objects are callable but are not functions:

     var obj = document.createElement('object'); typeof obj; // "function" --> It's callable obj instanceof Function; // false --> It's not a function 
  • Some objects are callable and are functions:

     function obj(){} typeof obj; // "function" --> It's callable obj instanceof Function; // true --> It's a Function instance 
  • Not all Function instances are callable:

     var obj = Object.create(Function.prototype); obj instanceof Function; // true --> It's a Function instance typeof obj; // "object" --> It's not callable obj(); // TypeError: obj is not a function 

It's just the way the language is designed. Functions are reference types (they are passed as pointers), and JavaScript reference types may have sub-references. I think you are struggling to reconcile a model of objects from C++ or Java (structs with privileged methods) with the type sugar another language provides.

I am not sure at what point Brendan Eich chose to implement functions as an instance of objects, but I suspect the reasoning was that it was consistent with making functions first-class variables. Objects already existed as a type of variable and it perhaps made sense to model functions using an existing variable type. You would have to ask him directly.

One handy side effect is that it allows us to store metadata on a function. This can be handy when performing caching or doing anything else that requires state to be held between function calls:

function myCachedFunction(argument) {
    myCachedFunction.cache = myCachedFunction.cache || {};
    myCachedFunction.cache[argument] = myCachedFunction.cache[argument] || operation();

    return myCachedFunction.cache[argument];

    function operation() {
        // performs action with argument
        // only gets called if no cache lookup for argument
    }
}

Some functions also need to know when they've been called. This can be achieved by closure variables, but function fields can sometimes be a more elegant solution:

function getUniqueID() {
    getUniqueID._calls = getUniqueID._calls || 0;
    return getUniqueID._calls++;
}

仅仅是因为它们是……这就是语言设计师决定要做的事情。

What would you expect to happen if an object were callable? You can think of an object as storage and a function as something you can execute. Also, functions are not objects but they are a superset of them. Due to this libraries like jquery are possible as is prototypical inheritance which is how you make a class in JavaScript.

function Car() {
    this.tires = 4;
}

Car.prototype.hi = function() {
    console.log("hi");
}

var myCar = new Car();

console.log(myCar.tires); // 4
myCar.hi(); // hi

And static methods

Car.bye = function() {
    console.log("bye");
}

Car.bye(); // bye
myCar.bye(); // this is an error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM