0

Now I know this might be a stupid question, but I need to improve my understanding of the language. So first, please have a look at the simple code:

JS:

function Blog(body , date){
    this.body = body;
    this.date = new Date(date);
}

Blog.prototype.toString = function(){
    return '[' + (this.date.getMonth() + 1) + '/' + this.getDate() + '/' + this.getFullYear() + ']' + this.body;
};

Now, we humans can clearly see that there is an object constructor for the Blog object, and there is a function that is owned by the Blog class. Now, end of the day, the constructor is still a function, a function which is written like any other function: same syntax, same kind of arguments etc.

Now here is my question: According to this, every function reference(which in this case, is Blog) can be a class. Is it true or not? And if that is not true, how does javascript know that Blog is a class and not just the reference to a function?

NOTE: I hope I made my point clear. If not, please tell me in the comments.

codetalker
  • 576
  • 1
  • 6
  • 21
  • 3
    There is no difference between a function and a class. – SLaks Dec 09 '15 at 18:23
  • 1
    there were never any "Classes" in js ,people used Pascal case for function names to specify constructors some called it class .but `class` keyword was added officially in js recently – Ramanlfc Dec 09 '15 at 18:25
  • 1
    might also be helpful to read the top answer here on what the `new` keyword actually does http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Matthew Dec 09 '15 at 18:29
  • @SLaks: Semantically, there is a difference between callable and constructable objects. Of course, in practise every `function` definition (expression or declaration) is both. – Bergi Dec 09 '15 at 18:34

2 Answers2

3

Every function can be invoked with the new keyword in JavaScript, so every function can be used as a constructor. However, only certain functions will create a useful object when called with new.

TbWill4321
  • 8,626
  • 3
  • 27
  • 25
1

Actually, nothing is a class in javascript. There are no classes. But "we humans" can pretend that they are classes. In that case, yes, every function can be a class ;)

See also: What techniques can be used to define a class in JavaScript, and what are their trade-offs?

Community
  • 1
  • 1
zvone
  • 18,045
  • 3
  • 49
  • 77