OOP syntax in js and using prototype

Asked by richard retyi

What is the difference between these pieces of code and which is preferable in which cases?


A
 

function Obj() {}
Obj.method = function(type) {
    return this.coords[type];
};
var obj = new Obj(),
    current = obj.method(type);

 

B
 
function Obj() {}
Obj.prototype.method = function(type) {
    return this.coords[type];
};
var obj = new Obj(),
    current = obj.method(type);



C
 
var obj = {
    method : function(type) {
        return this.coords[type];
    }
},
    current = obj.method(type);



D
 
function objMethod(type){
    return this.coords[type];
}
var obj = {
    method : objMethod
},
    current = obj.method(type);


added @ 1732:
E
 
function Obj() {
    this.method = function(type) {
        return this.coords[type];
    };
}
var obj = new Obj(),
    current = obj.method(type);

Answers

barbara grossman
JS is an object-oriented language, but there are no classes in it, they are replaced by object constructors, so instead of the usual inheritance through classes, there is inheritance through prototypes. Those. an instance of a class inherits its properties and methods, which are in its prototype.
The class constructor (function Obj () {}) is a function in which the properties and methods of the prototype are described, therefore all of them will be accessible when creating an instance.

In Example A, the constructor is empty, and Obj.method assigns a method to an object, not its prototype, so it will not be inherited by obj = new Obj (). This example does not work.

Example B is correct, here the method method is added to the prototype and will be inherited by all instances.

Example C is most often used when you need to implement singleton or namespace, because it is a simple hash without a constructor, you cannot inherit it. In fact, this is not an object in OOP understanding, but simply an associative array, which can contain any data, methods, and other objects.

Example D is similar to Example C, only its method property contains a link to an external function. This example can be used when you need to call a function from an external library.

Example E is correct and similar to example B, with the difference that the inherited method is specified immediately in the constructor, and not through the prototype.
Replies:
Very good answer, everything is detailed and great, thanks! - rachael
gallagher308comcast net
Well, in fact, the difference between B and E is, in case of E, when the method is declared directly in the constructor, it will have access to private variables and methods, these are the so-called privileged methods, but in example B there is no possibility to work with private data.
That's what I'm talking about:
var MyClass = function() {
  // Приватные атрибуты
  var _a, _b;
  // Приватный метод
  function _myPrivate(isbn) {
  } 
  // публичный привилегированный метод
  this.MyPublicPlus = function() {

  };
}

// публичный непривилегированный метод.
MyClass.prototype = {
  MyPublic: function() {
  }
};

The MyPublicPlus method will have access to _a, _b and _myPrivate (), but MyPublic will not ...
nils samuels
In general, anyone interested in how Javascript works, I advise you to read www.crockford.com/javascript/javascript.html
amelia wimmer
will be added to the prototype.
If you do not use it, you can create private properties and methods that will be accessible from other methods of the instance, but not directly.

 
function Obj() {
    var privateMethod = function(x) {
        return x;
    }
    this.publicMethod = function(x) {
      return privateMethod(x); 
   }
}
var obj = new Obj();
obj.privateMethod(1); // -> вызовет ошибку
obj.publicMethod(1); // -> вернет '1'

Replies:
In Example E, the method will not be added to the prototype.

Compare:
function Obj(){};
Obj.prototype.fnc = function(){alert(5)};
obj = new Obj();
obj.fnc(); // 5
Obj.prototype.fnc = function(){alert(51)};
obj.fnc(); //51


 

function Obj(){
  this.fnc = function(){
    alert(5);
  }
};
obj = new Obj();
obj.fnc && obj.fnc();
Obj.prototype.fnc = function(){alert(52)};
obj.fnc();


 javascript.ru/ecma/part13#a-13.2.2

Thus, the properties and methods specified inside the constructor will not fall into the prototype and will exist separately for each object (as opposed to prototype, which is common for all objects generated by this constructor). Those. Option E is more expensive in terms of memory, in contrast to option B.

 s43.radikal.ru/i101/1009/49/65ba9a6115f8.jpg
Memory consumption graph. The first bump is 1,000,000 instances of a class in which 3 methods are specified inside the constructor. The second mound is 1,000,000 copies, in which the same 3 methods are specified in the prototype. - jamie gavitt
anthony cast
A, B, E - there is a constructor Obj. in the case of a function call via new, the constructor will work with the new object, in the case of a call via call / apply it will expand the object you specify. those. one function can be both "class" and "admixture".
C, D - creation of the object by "hands", without a constructor. in D, the function is rendered and named - it is implied that it can be used not only as a method.
B - prototyping is used. each object has a prototype *, which means that non-primitive data types (functions, arrays, dates, objects) will be stored only in the prototype, saving memory and time to “create” an object, but slowing down the subsequent work with an object due to the fact that “common” data / methods will be accessed via (chain) prototypes.
A - the function is also an object, and the “method” is designated just at the function object. the object of the function (-constructor) is in no way associated with the objects it modifies. the designer’s place is a good place for any junk that you don’t want to distribute to all its “copies”.

a couple of points to realize:

  375915423
  375915423

read:
 link
* dklab.ru/chicken/nablas/40.html - .constructor.prototype; somewhere there was also an explanation for the need to put a prototype conctructor in the "current" class
 www.webreference.com/js/column26/apply.html - apply impurity
I also recommend to google about every typeof, instanceof, hasOwnProperty, isPrototypeOf, etc.

In what proportion to use prototypes, closures, impurities and other decorators - it is solely your style.
Wine, games and open ATI driver? :: How articles from Wikipedia are attached to GoogleMaps :: File manager for linux? :: Advise good books on Python'u focused on web development :: Calculate height (in pixels) of an NSTextField in Cocoa?
Leave Repply for OOP syntax in js and using prototype
Useful Links