Javascript call prototype functions

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.

Источник

Function.prototype.call()

The call() method calls the function with a given this value and arguments provided individually.

Try it

Syntax

call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) 

Parameters

The value to use as this when calling func . If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

Arguments for the function.

Return value

The result of calling the function with the specified this value and arguments.

Description

Note: This function is almost identical to apply() , except that the function arguments are passed to call() individually as a list, while for apply() they are combined in one object, typically an array — for example, func.call(this, «eat», «bananas») vs. func.apply(this, [«eat», «bananas»]) .

Normally, when calling a function, the value of this inside the function is the object that the function was accessed on. With call() , you can assign an arbitrary value as this when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.

Warning: Do not use call() to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means new.target is undefined , and classes throw an error because they can’t be called without new . Use Reflect.construct() or extends instead.

Examples

Using call() to invoke a function and specifying the this value

In the example below, when we call greet , the value of this will be bound to object obj , even when greet is not a method of obj .

function greet()  console.log(this.animal, "typically sleep between", this.sleepDuration); > const obj =  animal: "cats", sleepDuration: "12 and 16 hours", >; greet.call(obj); // cats typically sleep between 12 and 16 hours 

Using call() to invoke a function without specifying the first argument

If the first thisArg parameter is omitted, it defaults to undefined . In non-strict mode, the this value is then substituted with globalThis (which is akin to the global object).

.globProp = "Wisen"; function display()  console.log(`globProp value is $this.globProp>`); > display.call(); // Logs "globProp value is Wisen" 

In strict mode, the value of this is not substituted, so it stays as undefined .

"use strict"; globalThis.globProp = "Wisen"; function display()  console.log(`globProp value is $this.globProp>`); > display.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined 

Transforming methods to utility functions

call() is almost equivalent to a normal function call, except that this is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling array.map(callback) , you use map(array, callback) , which avoids mutating Array.prototype , and allows you to use map with array-like objects that are not arrays (for example, arguments ).

Take Array.prototype.slice() , for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

const slice = Array.prototype.slice; // . slice.call(arguments); 

Note that you can’t save slice.call and call it as a plain function, because the call() method also reads its this value, which is the function it should call. In this case, you can use bind() to bind the value of this for call() . In the following piece of code, slice() is a bound version of Function.prototype.call() , with the this value bound to Array.prototype.slice() . This means that additional call() calls can be eliminated:

// Same as "slice" in the previous example const unboundSlice = Array.prototype.slice; const slice = Function.prototype.call.bind(unboundSlice); // . slice(arguments); 

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 Jun 1, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Bind, Call и Apply в JavaScript

От переводчика:
Прошу принять во внимание, что приведенный здесь код, возможно, не является хорошими практиками. Тем не менее разбор сниппета из этого поста может оказаться еще одним поводом окунуться в функциональный JavaScript.

Недавно я увидел изящный JS сниппет в этом твите.

var bind = Function.prototype.call.bind(Function.prototype.bind); // #fp 

Взглянув на него, я смог догадаться, что он делает. Он превращает x.y(z) в y(x, z) . Радуясь как ребенок, я показал его своим коллегам. Они спросили меня, что же тут происходит. Я открыл рот, чтобы объяснить и… не смог сказать ни слова. Я развернулся и ушел.

В большинстве случаев, взглянув на хорошо написанный код, можно легко догадаться, что он делает. Имея какой-то опыт в функциональном JavaScript, прочитав «Functional JavaScript» и «JavaScript Allongé» (обе замечательны), у меня не возникло особых трудностей в его прочтении. Но как объяснить этот код кому-то без опыта функционального программирования?

Я решил поэтапно разобраться на простых примерах что же тут происходит. Результат был таков:

// Создадим простой объект, чтобы использовать его в качестве контекста var context = < foo: "bar" >; // Функция, которая возвращает свойство «foo» контекста «this» function returnFoo () < return this.foo; >// Свойства не существует в текущей области видимости, поэтому undefined returnFoo(); // => undefined // Но если мы свяжем эту функцию с контекстом var bound = returnFoo.bind(context); // Свойство теперь в области видимости bound(); // => "bar" // // Так работает Function.prototype.bind. // Так как returnFoo — это функция, она наследует прототип Function.prototype // // Существует несколько способов связывания функции с контекстом // Call и apply позволяют вам вызывать функцию с нужным контекстом returnFoo.call(context); // => bar returnFoo.apply(context); // => bar // Так же можно вложить функцию в объект context.returnFoo = returnFoo; context.returnFoo(); // => bar // // Теперь давайте немного усложним // // В Array.prototype есть замечательный метод slice. // При вызове на массиве он возвращает копию массива // от начального индекса до конечного (исключительно) [1,2,3].slice(0,1); // => [1] // Мы берем slice и присваиваем его локальной переменной var slice = Array.prototype.slice; // slice теперь оторван от контекста. Из-за того, что Array.prototype.slice // работает с данным ему контекстом «this», метод больше не работает slice(0, 1); // => TypeError: can't convert undefined to object slice([1,2,3], 0, 1); // => TypeError: . // Но мы можем использовать apply и call, они позволяют нам передавать нужный контекст slice.call([1,2,3], 0, 1); // => [1] // Apply работает как call, но принимает аргументы в виде массива slice.apply([1,2,3], [0,1]); // => [1] // Немного надоедает использовать .call каждый раз. Может воспользоваться bind? // Точно! Давайте привяжем функцию call к контексту slice. slice = Function.prototype.call.bind(Array.prototype.slice); // Теперь slice использует первый аргумент в качестве контекста slice([1,2,3], 0, 1); // => [1] // // Неплохо, правда? Но у меня осталась еще кое-что. // // Давайте проделаем с самим bind то же, // что мы делали со slice var bind = Function.prototype.call.bind(Function.prototype.bind); // Обдумайте то, что мы только что сделали. // Что происходит? Мы оборачиваем call, возвращая функцию, которая принимает функцию и контекст // и возвращает связанную с контекстом функцию. // Вернемся к нашему первоначальному примеру var context = < foo: "bar" >; function returnFoo () < return this.foo; >// И к нашему новому bind var amazing = bind(returnFoo, context); amazing(); // => bar // Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 

Источник

Читайте также:  Прозрачное меню для css
Оцените статью