Backbone developers often utilize various techniques to initialize functions in order to retrieve values more efficiently.
Backbone.Model.extend({
url: function() { return 'myurl.aspx'; }
});
// VS
Backbone.Model.extend({
url: 'myurl.aspx'
});
This approach is especially useful when there are calculations or conditions that need to be processed before determining the final URL.
Backbone.Model.extend({
url: function() {
if ( this.get('name') ) {
return 'service1.aspx';
}
else {
return 'service2.aspx';
}
}
});
In the comparison between the two examples, the first example passes an anonymous function as an argument to myFunction
, while the second example sends an object.
myFunction(function() {
return {
foo: 'bar'
};
}); // function() {...}
myFunction({
foo: 'bar'
}); // {foo: 'bar'}
function myFunction(what) {
console.log(what);
}
When discussing closures, a notable distinction is the ability to have private variables enclosed within the function:
var setGet = (function() {
var v = null;
return {
get: function() { return v; },
get: function(val) { v=val; },
};
});
// VS:
var setGet = {
v: null,
get: function() { return this.v; },
get: function(val) { this.v; },
};
In the first example, accessing the variable v
requires using .get
/.set
on setGet
, whereas in the second example, it can be directly modified by setting setGet.v = 'new_val';