Ben Aston
Ben Aston

Reputation: 55729

In JavaScript when does a function become a method?

In JavaScript does a function become a method when added as a property on an object, or is it the invocation of a function against an object that makes it a method?

Upvotes: 0

Views: 106

Answers (3)

Nikos M.
Nikos M.

Reputation: 8325

Technicaly, javascript does not have methods in the technical object-oriented way. Instead uses the prototype model of object inheritance (for example javascript does not have class inheritance but prototypical inheritance, does not support private methods etc etc, these are differences between the two models, e.g "Javascript, the good parts").

Anyway, any function added as property of an object can be called as the object's method e.g obj.my_method() and also this inside the function will dynamicaly have access to the current object

Another way to call a function as if it is a method is by using .call functionality. For example my_method.call(obj) This is also an alternative to having private methods in javascript. One can define a function which is not accessible as the object property, but can be called as if it is a method of the object, using .call to bind this inside the function to the current object. One can argue that any function when called this way (or similarly) is indeed a method, i will not argue about it nor say otherwise.

Mumbling about terminology is not coding. Have fun

Upvotes: -1

Wolph
Wolph

Reputation: 80031

Since every function is javascript is part of an object, technically they are all methods.

Personally I would put the difference on binding to an object, if you're binding a function to a specific scope, it's a method.

Upvotes: -1

Quentin
Quentin

Reputation: 943537

The definition in the specification is:

function that is the value of a property

Upvotes: 3

Related Questions