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.
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.
x.a
. , eat() a, :
eat()
a
function x() { this.a = 'a'; } x.prototype.eat = function() { // do stuff with this.a }
a, eat. ( ) , a x.
eat
x
, new. a , .
new
, :
function x() { this.a = 'a'; this.eat = function() {}; }
var y = new x();
- :
function x() { this.a = 'a'; } x.prototype.eat = function() {};
, , . , JS , . new .
{} , . :
{}
var myconstr = function(param){ var pr = 'some private var'; return { a : param, get2a : function(){ return this.a; } }; };
, .
, prototype, , , , , , - .
prototype