Suppose there is some func function that performs an action on an obj object (DOM node), for example, attaches a child to it.

Initially, I solved the problem through a stand-alone function of the form func(obj, param) but then I decided that it would be more convenient if I did this as an object method and hooked it как obj.func(param) , but as I understood, declare function as a method in advance, in order to "cling" it to any object you don’t want, you need to attach a method to an object in advance if you want to use it:

 obj: { func = function(param) { ... } } 

Why then do we need object methods? It looks like extra lines of code and extra space in memory.

  • Pro prototypes heard? - Stranger in the Q

3 answers 3

For example, there is a User object:

 let user = { name : "Ivan", surname : "Ivanovich", getFullName : function() { return `${this.name} ${this.surname}`; } }; console.log(user.getFullName()); 

Console: Ivan Ivanovich. Here is one of the examples of object methods; methods are also very useful when working with classes and inheritance.

    It is not necessary to immediately cling to the function, and so no one does it, everyone clings if they hook through a prototype

     Class.prototype.methodName = function () {} 

    then the function is not duplicated inside objects created through this class. And it is not necessary to immediately "cling", you can write at any time ..

    Differences complicates a lot of code for simple tasks and vice versa makes it easier for complex applications !!!!!!!!

      A simple function that takes everything necessary through arguments is more universal, since theoretically it does not have a state that would be stored between calls (although some manage to create it after all). The object method implies some state that exists with the object.

      Although the absence of such a state is cool, it is often less convenient. OOP is intuitive, and the fact that, for example, a Собака object can гавкать seems more natural than being able to гавкать with the help of Собаки .

      Well, in order to attach a method to an object there are many ways (there are good articles on OOP in js on learn.javascript.ru ). I like this:

       var Dog = function(name, voice) { // почти класс :-) this.name = name; // публичное свойство var _realName = name; // приватное свойство this.bark = function() { // публичный метод var name; if (this.name !== _realName) { name = this.name + ' (на самом деле ' + _realName + ')'; } else { name = this.name; } return name + ': ' + _bark(voice); } function _bark(voice) { // приватный метод return voice + '-' + voice; } }; var dog = new Dog('Шарик', 'гав'); alert(dog.bark()); dog.name = 'Лошарик'; alert(dog.bark());