Object declaration in Javascript

8
function List(){
   this.listSize = 0;
   this.pos = 0;
   this.dataStore = []; 
};

Can I consider this code snippet as creating a List object?

    
asked by anonymous 21.05.2015 / 00:29

2 answers

3

JavaScript is a multi-paradigm language. Among the supported paradigms is Object Orientation.

You can create objects in a variety of ways. In this form, I create a list object, with the listSize, pos, and dataStore properties, and a method called myMethod (). It is not a definition of a "class" (defining class as an object model), but only an object. In this form, each instance of List will have a copy of the myMethod () function.

function List() {
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = [];
    this.myMethod = function () {
        alert('Este é um método');
    };
}

var list = new List();

The way I use to define a class is through prototypes, where you create a "prototype" of a function, and later create objects that are instances of this prototype.

List = function () {
    this.dataStore = [];
};

List.prototype.listSize = 0;

List.prototype.pos = 0;

List.prototype.myMethod = function () {
    alert('Este é um método');
};

var list = new List();

Using this form will consume less memory because the definition of myMethod () (and other variables) is shared among all objects that use this object prototype. In addition, editors who have auto-complete will identify that their object has this function / property: -).

UPDATE: Fixed as seen by @bfavaretto and Optimizing JavaScript Code .

    
21.05.2015 / 16:14
8

No. That is a function. It could be called informally "class List ", if the intention is to use it as a constructor function, with the new operator. In this use, then you will be creating an object of type List (or "an instance of List "):

function List(){
   this.listSize = 0;
   this.pos = 0;
   this.dataStore = []; 
};
var objetoLista = new List();
    
21.05.2015 / 00:38