2

I'm new to JavaScript and Node.js and am learning OOP and came across two ways of calling a method.

My code:

var Person = function(name) {
    this.fName = name;
};

Person.prototype.sayHello = function(){
    console.log("Hello, I am " + this.fName);
}

var person1 = new Person("mike");
person1.sayHello();

var helloFunction = person1.sayHello;
helloFunction.call(person1);

Output:

Hello, I am mike
Hello, I am mike

Both uses produce the same results. Is there a situation where one version would be more proper than the other? Are there any advantages/disadvantages to the two calls?

Mike G
  • 33
  • 6
  • `Proper` way of doing things is debatable. It all depends on your use case. Try to follow one convention only unless you can't avoid it. – stackErr Apr 13 '16 at 20:41
  • As a side note, see [this](http://stackoverflow.com/questions/35949554/invoking-a-function-without-parentheses) – Amit Apr 13 '16 at 20:50
  • 1
    The second way is useful if you need to call `sayHello` bound to another `this` context that contains a `fName` property also. Other than that, try to follow the first way you've found and also have a look at the `class` and `extends` keywords introduced in 2015. – Chiru Apr 13 '16 at 20:50
  • @Amit I will look into those, thanks for the help. – Mike G Apr 13 '16 at 20:54

3 Answers3

1

Is there a situation where one version would be more proper than the other?

You'd almost exclusivity use the normal, func() when calling a function. Using func.call() is not meant to be used without special reason, particularly, using a specific object as the this value.

Arbitrary usage of non-standard coding patterns creates unreadable, unmaintainable, bug prone code.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • This. Using .call makes me think that the function is an entirely different object with a method called call() that i'm simply not aware of on first glance. – hownowbrowncow Apr 13 '16 at 20:46
0

Both are legit. It depends on what endgame is for the results. Using .call is useful when you want to reuse a method from one object on another.

ryanve
  • 50,076
  • 30
  • 102
  • 137
0

In general, you would use person1.sayHello(). It's more concise and easier to read.

Where you would want to use sayHello.call is if the object has the fName property but does not itself have a sayHello method. For example:

var helloFunction = person1.sayHello;
var pseudoPerson = { fName: "shadow mike" };
helloFunction.call(pseudoPerson); // "Hello, I am shadow mike"
andyk
  • 1,628
  • 15
  • 12