Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If there is no distinction between classes and objects why doesn't this code work?

I was always taught that in Javascript there is no distinction between objects and classes. Then can someone explain why this code generate error:

var firstObj = function() {};

firstObj.prototype.sayHi = function() {
document.write("Hi!");
};

firstObj.sayHi();

Whereas this one works:

var firstObj = function() {};

firstObj.prototype.sayHi = function() {
document.write("Hi!");
};

new firstObj().sayHi();

What's the difference? Why isn't the first one working?

like image 735
user1883212 Avatar asked Aug 10 '26 02:08

user1883212


1 Answers

The key issue here is that your firstObj variable is a Function object, not a firstObj object. This is a subtle distinction, but the type of object determines which prototype it inherits.

The prototype is like a template that is applied to newly created objects of a particular type. You must create a firstObj object (usually with new which invokes the constructor and assigns a prototype) in order to have that template applied to it. In the first example, your firstObj variable is a Function object, not a firstObj object so it has the prototype of a Function not of anything else..

In your second example, you actually create a firstObj object so it inherits the prototype for that type of object.

If you want the method applied in your first example so it works on the function object you've already created, just put the method directly on your already existing function object, not on the prototype.

like image 174
jfriend00 Avatar answered Aug 11 '26 17:08

jfriend00