Javascript literal vs function oop

What are the best practices for using them?

var x = { a: 'a', eat: function() { }, ... }

against

var x = function() { var a = 'a'; this.eat = function() { }}

You must do the following:

new x();

Can someone help me explain the importance of these two, and which one is the preferred choice in the oop community? any word of wisdom would help. I also did some research, but nothing worked. many thoughts are welcome.

+5
source share
3 answers

The main difference is that the first version provides the variable "a", and the second hides it. Therefore, if you do not need or need client code to access x.a, the second version is preferred.

. , eat() a, :

function x() {
    this.a = 'a';
}

x.prototype.eat = function() {
    // do stuff with this.a
}

a, eat. ( ) , a x.

+4

, new. a , .

, :

function x() {
  this.a = 'a';
  this.eat = function() {};
}

, :

var y = new x();

- :

function x() {
  this.a = 'a';
}

x.prototype.eat = function() {};
+3

, , . , JS , . new .

{} , . :

var myconstr = function(param){
    var pr = 'some private var';
    return {
         a : param,
         get2a : function(){ return this.a; }
    };
};

, .

, prototype, , , , , , - .

+2

All Articles