Skip to content Skip to sidebar Skip to footer

Declaring And Assigning A Function Object With Object Keys In One Line

Is it possible to condense the following into a single statement? var foo = function () { return; }; foo.bar = 'baz'; The closest I came was: var foo = Object.create(function(){re

Solution 1:

You can do this with a function that copies attributes from one object to another and returns the modified object. This is a feature of most general-purpose JS libraries, and it's usually called "extend".

Underscore:

var foo =       _.extend( function () { return; }, { bar: 'baz' } );

jQuery:

var foo =       $.extend( function () { return; }, { bar: 'baz' } );

Prototype:

var foo =  Object.extend( function () { return; }, { bar: 'baz' } );

Angular:

var foo = angular.extend( function () { return; }, { bar: 'baz' } );

Ext:

var foo =      Ext.apply( function () { return; }, { bar: 'baz' } );

Post a Comment for "Declaring And Assigning A Function Object With Object Keys In One Line"