简体   繁体   中英

How does Javascript know which function reference is a class?

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.

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 .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM