decl
?
decl
is a javascript function that creates a prototype object and returns its constructor.
decl
used?
decl
takes a single argument named "declaration."
The declaration argument can either be an object literal,
or a function that constructs an equivalent object when invoked with new
.
Any properties created in the declaration will be copied to the prototype of the constructor function before it is returned.
// object literal
var Point = decl({
x: 0,
y: 0,
moveBy: function(x, y){
this.x += x;
this.y += y;
}
});
// "metaconstructor"
var Point = decl(function(){
this.x = 0;
this.y = 0;
this.moveBy = function(x, y){
this.x += x;
this.y += y;
};
});
The object literal style is more terse, but the "metaconstructor" style is more forgiving (semicolons vs commas, ASI) and offers some additional sugar for inheritance.
The "metaconstructor" style also provides a closure for
internal functions, variables, references to this
,
etc.
You can find more examples on the examples and unit tests pages.
decl
?
Dojo's declare
is similar to decl
.
A declare
example from the
dojo documentation, and a decl
example:
// dojo.declare
dojo.declare("Person", null, {
constructor: function(name, age, residence){
this.name = name;
this.age = age;
this.residence = residence;
},
moveToNewState: function(newState){
this.residence = newState;
}
});
// decl
var Person = decl({
constructor: function(name, age, residence){
this.name = name;
this.age = age;
this.residence = residence;
},
moveToNewState: function(newState){
this.residence = newState;
}
});
These code blocks look very similar. What's different about decl
?
decl
is simple
The most noticeable difference is that decl
's
syntax is easier to remember; it only takes one parameter and
returns the result, instead of assigning the result to
a variable identified by a string in the first parameter.
One of decl
's main goals is to provide a syntax which is
both easy to learn and easy to remember.
decl
is fast Constructors returned by decl
are able to
instantiate new objects
much faster
than those produced by dojo.declare
.
They perform as well as if they had been declared in plain old javascript.
The constructors created by Dojo are only able to create new
objects at about 12% of the speed of their decl
counterparts.
decl
doesn't pollute
The constructors and prototypes created by decl
don't have
any properties other than the ones you define.
By contrast, dojo.declare
creates properties in
the constructor (_meta
and extend
)
and the prototype (__inherited
,
declaredClass
, getInherited
,
inherited
, isInstanceOf
, and
superclass
).
Dojo users interested in decl can find more information here.