ram
6/14/2015 11:59:00 PM
Angel Rodriguez <cimadelmundo3000@gmail.com> writes:
>I'm working on a project, and I am defining my style of
>programming functions in javascript. With what I have
>studied, I have seen three methods for working with functions
>and I would like to know what kind of method you would use
>considering scalability, performance, maintenance, etc.
There are actually 28 ways to create objects in JavaScript.
For example, here is another one of them:
I want to define a simple counter object that has
a method that can count upwards by 1.
JavaScript is prototype-based, not constructor-based.
So, we can always ignore constructors and just work
with the prototypes!
I create my global prototype:
var counterPrototype = Object.create( Object.prototype );
. I add my counter method »inc« to the prototype:
Object.defineProperty
( counterPrototype, "inc",
{ value: function()
{ "use strict"; return this.v++; },
configurable: true,
enumerable: false,
writable: true });
. I create new object from my prototype:
var newCounter = Object.create( counterPrototype );
. It still needs a field »v« with the counter value:
Object.defineProperty
( newCounter, "v",
{ value: 0, configurable: true, enumerable: true, writable: true });
. Done! I can now count:
newCounter.inc();
newCounter.inc();
newCounter.inc();
. We have not used constructors, so »newCounter.constructor.name«
is »Object«.
If you often create objects in this manner, of course, you can
put some parts of the above into a library, so that you then can
create objects in this way even more easily.
Advantages of this method: You have more control of the details.
For example, instead of »Object.prototyp« above, I could have
used »null«. Everything above would still work, but now
»newCounter.constructor.name« would be undefined. And at some of
the places above I could have used other values for »configurable«,
»enumerable« or »writable«.