Sandeep Gupta
Sandeep Gupta

Reputation: 7250

Working of Date in Javascript

I recently learned that we can't access inner function directly. We need to make the object of the function to do that. However it looks different to me in Date function since we can access inner functions like Date.now().typeof Date returns "function" and not "Object".

What am I missing here?

Upvotes: 0

Views: 67

Answers (3)

Cecil
Cecil

Reputation: 351

The inner function mostly is a constructor Function.

e.g: function MyDate () { } MyDate.prototype.getDate = function () { console.log('getDate') } MyDate.getDate() // getDate

Upvotes: -1

Suren Srapyan
Suren Srapyan

Reputation: 68685

You can make a such thing. Here b function is a function of the A. Typeof A will return function. But in Javascript functions are also objects. So you can add properties and functions(methods) to the function object itself.

function A(){
  
}

A.b = function(){
  console.log('B');
}

A.b();

But if you mean inner function to this

function A(){
  
  function b(){
    console.log('b')  ;
  }
  
}

You can't access the inner b function outside the A .

One case to access the inner function outside the A, you need to assign the function to the this, which is called method, then create an object of A and use that method.

function A(){
      
  this.b = function (){
    console.log('b');
  };
      
}

let a = new A();
a.b();

Upvotes: 5

Chu Ya'an Xiaonan
Chu Ya'an Xiaonan

Reputation: 95

Actually, Date is the constructor of the Object Date, so it is a common sense that you use new Date() to get access into these 'inner functions' you referred in your question:

type of Date // function
type of Date() // string, shorthand of new Date().toString()
type of new Date() // object

Upvotes: -1

Related Questions