JavaScript User defined object

How can we use a JavaScript function as an object?

This tutorial will teach us to use the JavaScript functions as an object. However, functions, objects, and arrays are the mutable data types in JavaScript, and all mutable data types are the objects.

The JavaScript object is one type of entity that contains the key-value pairs. It contains unique keys; every key has some values that can be of any type. We can use the object key to access the values of the objects.

We can create a function so that it behaves like an object. Below, we have given a detailed explanation of converting the function to an object.

Use JavaScript function as an object

In this section, we will learn basic things to make functions works as an object in JavaScript. We can define the variables inside the function and initialize the values of variables of the key. To create a new object, we will create an instance of the object by passing the arguments we need inside the function to initialize the key values.

Syntax

Users can follow the below syntax to use the function as an object.

function funcObject() < this.key1 = "hello"; this.key2 = "world"; >Var object = new funcObject(); let value = object.key1; // accessing the object key values

Parameters

  • this − It is the reserved keyword in JavaScript. This keyword refers to the variable, object, or method of the current instance. It means that if we use this keyword inside the function or block, it refers to the variable of that block only. If we use this keyword globally inside the code, it refers to the global variable.
Читайте также:  Tsv to csv python

Example

In the below example, we have created a single function. We will create the instance of the function and use it as an object. After that, using the object of the function, we will access the variables of the function as we access the values of the normal object using keys.

      

JavaScript function as an object

Values of the object, after using function as an object.

In the above example, the function works the same as the object. We have accessed the function variables as we access the values of the object keys, and it prints the above output on the screen.

Add parameters and methods inside the function

In this section, we will add the parameters to the function. Using the parameters of the function, we can initialize the object’s keys by the parameters. We will pass the arguments to instances of the object when we create a new object using the ‘new’ keyword.

Rather than creating a normal object, using the function as an object has more benefits. When we use the parameterize function as an object, we can create a new object with different values by passing the values of keys as an argument. If we use a normal object, we need to re-initialize the value for every key.

Syntax

Users can follow the below syntax to declare method inside the function which we use as an object.

function funcObject(param1, param2) < this.key1 = param1; this.key2 = param2; this.method = function () < // code for current method >> // object of the function with arguments let newObject = new funcObject( "hello", "world" ); newObject.method(); // invoking the method of the object

Example 2

In the below example, we have created the function with parameters. Also, the function contains the method which we have assigned to the variable. We have created the anonymous method to assign it to the variable. After that, we have created the instance of the object using the function by passing the arguments.

   

Use Javascript function as an object.

Create method inside the function, initialize value of the function variable, and use it as an object.

Conclusion

We have learned to use the function as an object. Here, this keyword plays an important role in creating variables of the current function. When using the user-define objects, it is better to manage the objects with multiple values. Furthermore, we can pass the values to initialize the key and create the new object just with a single line of code.

Читайте также:  text-align

Источник

Магия JavaScript: arguments

arguments — очень специфическая штука, о которой новички и даже любители знают только то, что это «вроде массив, но какой-то неправильный». На самом деле, у него есть ряд интересных особенностей. Предлагаю в топике пофантазировать на тему TypeHinting, аргументов по-умолчанию и всякого другого.

А также покажу интересную идею-библиотеку

function test (foo, bar) < Args(arguments).defaults(100, 100); return [foo, bar]; >; test( ); // 100, 100 test(15 ); // 15, 100 test(21, 42); // 21, 42 

В первую очередь хотел бы заметить, что множество идей высказанных в топике являются достаточно спорными. Я сам не уверен, что буду ими пользоваться и не советую пользоваться новичкам.

Что такое arguments

Сделать из него массив просто:

var array = Array.prototype.slice.call(arguments, 0); // или покороче, но менее производительно: var array = [].slice.call(arguments, 0); 

Мы вызываем метод slice прототипа Array от лица arguments .

Что есть в arguments

var count = function () < console.log(arguments.length); >; count(); // 0 count(first, second); // 2 

Не забывайте, что у каждой функции тоже есть свойство length , которое указывает на то, сколько элементов объявлено в её заголовке:

function one (foo) <>; function three (foo, bar, qux) <>; console.log( one.length); // 1 console.log(three.length); // 3 

arguments.callee — ссылка на саму функцию.

Таким образом можно проверить, передано ли правильное количество элементов, или нет:

function test (foo, bar, qux) < return arguments.callee.length === arguments.length; >test(1); // false test(1,2,3); // true 

Аргументы в arguments

function test (foo, bar) < console.log(foo, bar); // 'a', 'b' console.log(arguments[0], arguments[1]); // 'a', 'b' >test('a', 'b'); 

Теперь к интересному. Многие не знают, что объект arguments — содержит на самом деле ссылки, а не значения, и тесно связан с аргументами:

Читайте также:  Book to learn html pdf

При этом связь достаточно крепкая:

function foo (qux) < change(arguments); return qux; >; function change(a) < a[0] = 42; >foo(10); // 42 

Что из этого можно получить?

function ($foo = 30, $bar = 'test')

В javascript оно будет выглядеть как-то так:

Зная особенности arguments можно создать красивый интерфейс:

function test(foo, bar) < Args(arguments).defaults(30, 'test'); console.log(foo, bar) >test(); // 30, 'test' 
 function Args (args) < if (this instanceof Args) < this.args = args; >else < // Если создано не через new, а просто вызвана функция, создаем и возвращаем новый объект return new Args(args); >>; Args.prototype = < defaults: function () < var defaults = arguments; for (var i = defaults.length; i--;) < if (typeof args[i] === 'undefined') args[i] = defaults[i]; >return this; > >; 

Аналогично можно сделать автоматическое приведение типов:

function test(foo) < Args(arguments) .defaults(10) .cast(Number); console.log(foo) >test('0100'); // 100 
function test(foo, bar) < Args(arguments).types(Foo, Bar); // code >test(new Foo(), new Bar()); test(1, 2); // Error 

Из интересных идей — сообщение, что все аргументы обязательны:

function test (foo, bar, qux) < Args(arguments).allRequired(); >test(1,2,3); // success test(1,2); // Error: 3 args required, 2 given 

Заключение

Все эти идеи и возможности (и даже больше) я оформил в библиотеку — Args.js.
Согласен, что кое-какие вещи (как TypeHinting) не совсем подходят к идеологии языка. В то же время например defaults — очень удобная штука, имхо.
Пока что это прототип и, перед тем как вы будете его использовать — будьте уверены, что оно вам действительно нужно, а не что вы просто стараетесь из прекрасного языка сделать что-то похожее на C#.
Предлагаю обсудить, покритиковать код, найти пару багов и закоммитить несколько строк кода)

Args.js

К сожалению, из-за бага в трёх популярных браузерах(IE, Fx, Opera) я не смог добиться желаемого эффекта, полноценно самое вкусное заработало только в Chrome (ну по крайней мере в node.js работать будет)). Надеюсь, решим эту проблему вместе.

UPD: В комментах выяснили, что таки это бага Хрома, но, зато, какая приятная! Спасибо jamayka

Источник

Оцените статью