What is meant by 'first class object'?

后端 未结 11 1572
生来不讨喜
生来不讨喜 2020-11-22 10:46

In a recent question, I received suggestions to talk on, amongst other things, the aspect of JavaScript where functions are \'first class\' objects. What does the \'first c

11条回答
  •  半阙折子戏
    2020-11-22 10:56

    JavaScript functions are first-class functions meaning functions and objects are treated as the same thing. Functions can be stored as a variable inside an object or an array as well as it can be passed as an argument or be returned by another function. That makes function "first-class citizens in JavaScript"

    JavaScript uses literal notation syntax which makes it hard to fully grasp the fact that in JavaScript functions are objects.

    For example..

    var youObj1 = new Object();
    // or
    var youObj1 = {};
    

    both declerations are equivalent. By using new we are calling the constructor function of an Object. Also by using {} (JavaScript shortcut called literals) we are calling the construction function of an Object. {} is just a shorter representation for instantiating the constructor.

    Most languages uses new keyword to create an object, so lets create a JavaScript object.

    var myFunction = new Function("a",  "b", 'return a_b');
    

    As you see we created an object name function.

    Creating same object name function using JavaScript function expression..

    var myFunction = function myFunction(a,b) {
        return a+b;
    }
    

    Here we go we just created a object name function.

提交回复
热议问题