(full code in this github repo )
In you do not know the series of JS booklets (in particular, the name of this & Object Prototypes), as well as in many SO answers (for example, this one ), the point is often made that there is no such thing as “constructor functions”, but rather ordinary functions, called by the "constructor call". I am trying to understand this point by creating vanilla functions that are not meant to be called using newto create my objects.
The first attempt works:
var assert = function(condition, message) {
if (!condition)
throw new Error(message||'assertion error');
};
var Counter1 = function() {
var count = 0;
return {get: function() {return count;},
inc: function() {count++;}};
};
var c2a = Counter1();
c2a.inc();
assert(c2a.get()===1);
var c2b = Counter1();
assert(c2b.get()===0);
assert(c2a.get()===1);
, getter/setter ( ):
var Counter2 = function Counter2_() {
var count = 0;
Counter2_.prototype.get = function() {return count;};
Counter2_.prototype.inc = function() {count++;};
assert(Counter2_.prototype.constructor === Counter2_);
var rv = {};
rv.__proto__ = Counter2_.prototype;
return rv;
};
var c = Counter2();
c.inc();
assert(c.get()===1);
assert(Object.getPrototypeOf(c)===Counter2.prototype);
var cb = Counter2();
assert(Object.getPrototypeOf(cb)===Counter2.prototype);
assert(cb.get()===0);
assert(c .get()===1, 'expecting c to be 1 but was:'+c.get());
.
, , , Counter2 get , , count ( 0). , , Counter2 ( , ).
, Counter2 , count :
var Counter3 = function Counter3_() {
var count = 0;
var rv = {};
rv.__proto__ = Counter3_.prototype;
return rv;
};
Counter3.prototype.get = function() {return count;};
Counter3.prototype.get = function() {return this.count;};
:
1) - , Counter2 ?
2) (.. "vanilla", new), / , ?