Ad

Why Adding A Method To JavaScript Reference Type Like This Doesn't Work?

- 1 answer

Let's say I have such constructor:

function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
}

And I want to add methods to it.

Why this:

Person.prototype.getFullName = function() {
    return this.firstName + " " + this.lastName;
};

Is the way to do it, and not this:

Person.getFullName = function() {
    return this.firstName + " " + this.lastName;
};

I have no idea why I am getting downvoted, so I would appreciate if downvoters would add comments with the actual reason of downvote. This will help me phrase my future questions better.

I do understand the inheritance concept behind prototyping to some extent. At least to the extent shown in tutorials, articles and books in beginner level.

What confuses me is probably my background in Java and the class term, which is not the same thing in JavaScript.

I imagine that this defines a class Person:

function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
}

When I create an object using that class:

var myObject = new Person("John", "Doe");

I can still add some new properties or methods to that object:

myObject.getFullName = function() {
    return this.firstName + " " + this.lastName;
};

Now only myObject will have this new method getFullName, pretty clear.

var myObject2 = new Person("Daniel", "Cook");

For myObject2 there is no getFullName method, still clear.

Once I add a method to the prototype of my "class" Person it will be inherited by all objects created with that "class":

Person.prototype.getFullName = function() {
    return this.firstName + " " + this.lastName;
};

Now even myObject2, has the getFullName method. Clear.

Ok. I think I am comming to the root of the problem in my head. Extending this post helped me.

The function Person is also an object, right?

Ad

Answer

myObject.methodName = function() {}; adds a method named methodName to object myObject. That means that you can call it directly from the myObject and you don't need to create an instance.

To put it simply, you just call it by doing this :

myObject.methodName();

myObject.prototype.methodName = functioprototype.methodName = function() {}; adds a method named methodName to the prototype of object myObject. That means it exists for every instance of myObject, but you cannot call it directly from the myObject.

You call it by doing this :

var someInstance = new myObject();
someInstance.methodName();

In this case, myObject.methodName(); would generate an error!


Both are valid ways to implement an object on JavaScript. There's just a different concept behind them.

For a more in depth look into the difference between both approaches, I recommend you take a look at my article The many ways to implement OOP in Javascript.

Ad
source: stackoverflow.com
Ad