Showing posts with label Advanced-FunctionObject. Show all posts
Showing posts with label Advanced-FunctionObject. Show all posts

Friday, April 27, 2018

Function Object with Custom Properties

We can add our own custom properties with function object.

Below example will explain you How do we use custom property with function object.


function countTest() {
  alert("Hi");

  countTest.counter++;
}
countTest.counter = 0; // initial value

countTest(); // Hi
countTest(); // Hi

alert( `Called ${countTest.counter} times` ); // Called 2 times

Explanation :

We are calling countTest function at two times. So while calling at every time counter (custom property) will be executed and returning 2 in alert.


Function object - length property

Using length property with function object, will return how many parameters the function using.

Example:


function first(a) {}
function second(a, b) {}
function multiple(a, b, ...more) {}

alert(first.length); // 1
alert(second.length); // 2
alert(multiple.length); // 2

Note: The last one, multiple function showing parameter length as 2. Because rest parameters(...) will not be calculated.


Thursday, April 26, 2018

Function Object - name property


Function objects contain some properties.

1. name property

We can access a function’s name with the help of the “name” property.


function testFunctionName() {
  alert("Hi");
}

alert(testFunctionName.name); //testFunctionName


let sayHi = function() {
  alert("Hi");
}

alert(sayHi.name); // sayHi

Above code, you can see we are getting the function name with the help of name property.


It will work with function which is placed inside object too. See below to understand further,


let user = {

  sayHi() {
    // ...
  },

  sayWelcome: function() {
    // ...
  }

}

alert(user.sayHi.name); // sayHi
alert(user.sayWelcome.name); // sayWelcome


Note: Suppose if there is no name for function then empty string will be returned.