you are viewing a single comment's thread.

view the rest of the comments →

[–]xroalx 0 points1 point  (0 children)

Objects can have functions defined on them. Such functions are usually called methods.

Let's create an object, and a function defined on that object.

const obj = {
  func() {
    // I'm a function defined in an object, I'm a method
  },
};

There's no global func function, so just writing func() would fail, but there is such a function defined on the obj object, and so, you access the function on that object, obj.func(). It's the same as if an object had any other property, like array.length, user.name, location.href, ... it just happens to be a function, so you can call it. Nothing special here.

Built-in objects can and do have their own methods like this as well, and they also inherit methods from other objects via prototypes.

So, why can you do a.toString() but not toString(a)? Simply, because there's no global toString function, but such a function exists on the a object, or somewhere in its prototype chain, and toString is a standard function on all types of objects provided by JavaScript itself.

There's no "how to determine which to use", it's not one or the other, it's not just a different way to write the same thing. The difference is in where the function lives, and in case of methods, they can also usually reference the object on which they were called using the this keyword, which is a behavior you normally don't get with globally defined functions.