Function constructors in javascript

Function

The Function object provides methods for functions. In JavaScript, every function is actually a Function object.

Constructor

Creates a new Function object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval() . However, unlike eval() , the Function constructor creates functions that execute in the global scope only.

Instance properties

These properties are defined on Function.prototype and shared by all Function instances.

Represents the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the arguments property throws a TypeError . Use the arguments object inside function closures instead.

Represents the function that invoked this function. For strict, arrow, async, and generator functions, accessing the caller property throws a TypeError .

The constructor function that created the instance object. For Function instances, the initial value is the Function constructor.

These properties are own properties of each Function instance.

The display name of the function.

Specifies the number of arguments expected by the function.

Used when the function is used as a constructor with the new operator. It will become the new object’s prototype.

Instance methods

Calls a function with a given this value and optional arguments provided as an array (or an array-like object).

Creates a new function that, when called, has its this keyword set to a provided value, optionally with a given sequence of arguments preceding any provided when the new function is called.

Calls a function with a given this value and optional arguments.

Returns a string representing the source code of the function. Overrides the Object.prototype.toString method.

Specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor’s instances. Called by the instanceof operator.

Examples

Difference between Function constructor and function declaration

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created. This is different from using eval() with code for a function expression.

// Create a global property with `var` var x = 10; function createFunction1()  const x = 20; return new Function("return x;"); // this `x` refers to global `x` > function createFunction2()  const x = 20; function f()  return x; // this `x` refers to the local `x` above > return f; > const f1 = createFunction1(); console.log(f1()); // 10 const f2 = createFunction2(); console.log(f2()); // 20 

While this code works in web browsers, f1() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not the global scope, and x will be local to the module.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 18, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Constructor, operator «new»

The regular <. >syntax allows us to create one object. But often we need to create many similar objects, like multiple users or menu items and so on.

That can be done using constructor functions and the «new» operator.

Constructor function

Constructor functions technically are regular functions. There are two conventions though:

  1. They are named with capital letter first.
  2. They should be executed only with «new» operator.
function User(name) < this.name = name; this.isAdmin = false; >let user = new User("Jack"); alert(user.name); // Jack alert(user.isAdmin); // false

When a function is executed with new , it does the following steps:

  1. A new empty object is created and assigned to this .
  2. The function body executes. Usually it modifies this , adds new properties to it.
  3. The value of this is returned.

In other words, new User(. ) does something like:

function User(name) < // this = <>; (implicitly) // add properties to this this.name = name; this.isAdmin = false; // return this; (implicitly) >

So let user = new User(«Jack») gives the same result as:

Now if we want to create other users, we can call new User(«Ann») , new User(«Alice») and so on. Much shorter than using literals every time, and also easy to read.

That’s the main purpose of constructors – to implement reusable object creation code.

Let’s note once again – technically, any function (except arrow functions, as they don’t have this ) can be used as a constructor. It can be run with new , and it will execute the algorithm above. The “capital letter first” is a common agreement, to make it clear that a function is to be run with new .

If we have many lines of code all about creation of a single complex object, we can wrap them in an immediately called constructor function, like this:

// create a function and immediately call it with new let user = new function() < this.name = "John"; this.isAdmin = false; // . other code for user creation // maybe complex logic and statements // local variables etc >;

This constructor can’t be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.

Constructor mode test: new.target

The syntax from this section is rarely used, skip it unless you want to know everything.

Inside a function, we can check whether it was called with new or without it, using a special new.target property.

It is undefined for regular calls and equals the function if called with new :

function User() < alert(new.target); >// without "new": User(); // undefined // with "new": new User(); // function User

That can be used inside the function to know whether it was called with new , “in constructor mode”, or without it, “in regular mode”.

We can also make both new and regular calls to do the same, like this:

function User(name) < if (!new.target) < // if you run me without new return new User(name); // . I will add new for you >this.name = name; > let john = User("John"); // redirects call to new User alert(john.name); // John

This approach is sometimes used in libraries to make the syntax more flexible. So that people may call the function with or without new , and it still works.

Probably not a good thing to use everywhere though, because omitting new makes it a bit less obvious what’s going on. With new we all know that the new object is being created.

Return from constructors

Usually, constructors do not have a return statement. Their task is to write all necessary stuff into this , and it automatically becomes the result.

But if there is a return statement, then the rule is simple:

  • If return is called with an object, then the object is returned instead of this .
  • If return is called with a primitive, it’s ignored.

In other words, return with an object returns that object, in all other cases this is returned.

For instance, here return overrides this by returning an object:

function BigUser() < this.name = "John"; return < name: "Godzilla" >; // alert( new BigUser().name ); // Godzilla, got that object

And here’s an example with an empty return (or we could place a primitive after it, doesn’t matter):

function SmallUser() < this.name = "John"; return; // alert( new SmallUser().name ); // John

Usually constructors don’t have a return statement. Here we mention the special behavior with returning objects mainly for the sake of completeness.

By the way, we can omit parentheses after new :

Omitting parentheses here is not considered a “good style”, but the syntax is permitted by specification.

Methods in constructor

Using constructor functions to create objects gives a great deal of flexibility. The constructor function may have parameters that define how to construct the object, and what to put in it.

Of course, we can add to this not only properties, but methods as well.

For instance, new User(name) below creates an object with the given name and the method sayHi :

function User(name) < this.name = name; this.sayHi = function() < alert( "My name is: " + this.name ); >; > let john = new User("John"); john.sayHi(); // My name is: John /* john = < name: "John", sayHi: function() < . >> */

To create complex objects, there’s a more advanced syntax, classes, that we’ll cover later.

Summary

  • Constructor functions or, briefly, constructors, are regular functions, but there’s a common agreement to name them with capital letter first.
  • Constructor functions should only be called using new . Such a call implies a creation of empty this at the start and returning the populated one at the end.

We can use constructor functions to make multiple similar objects.

JavaScript provides constructor functions for many built-in language objects: like Date for dates, Set for sets and others that we plan to study.

In this chapter we only cover the basics about objects and constructors. They are essential for learning more about data types and functions in the next chapters.

After we learn that, we return to objects and cover them in-depth in the chapters Prototypes, inheritance and Classes.

Источник

Читайте также:  Portfolio html source code
Оцените статью