want to show all string properties of an object in JavaScript?
function showAllStringPropertiesOf( object ) {
for (var property in object) {
if (typeof object[property] == "string") {
console.log(property, ":", object[property]);
}
}
}
var object1 = {
name: "Spiragram",
address: "87 Beach Road",
vision: "Spiragram will liberate, lead and inspire programmers to realize their full potential ..."
},
object2 = {
name: "Tien Dung",
age: 26,
saySomething: function () { alert("hello from " + this.name); }
};
showAllStringPropertiesOf(object1);
showAllStringPropertiesOf(object2);
is it nice if we do not have to duplicate the function name? We can write:
forEach([object1, object2], showAllStringPropertiesOf );
where forEach is a funtion:
function forEach( a, fn ) {
var i, l = a.length;
for (var i = 0; i < l; i++)
fn(a[i]);
};
is there a better way (because we have only two objects)? The answer is making the function chainable by adding a return itself command to the end of the function.
function showAllStringPropertiesOf ( ... ) {
...
...
return arguments.callee;
}
now we can call:
showAllStringPropertiesOf( object1 )( object2 )
still want to make it more readable?
Let make more fun with “and” keyword.
showAllStringPropertiesOf( object1 ).and ( object2 );
by adding some code below
function showAllStringPropertiesOf ( ... ) {
...
...
return addAndMagicTo(arguments.callee);
}
function addAndMagicTo( fn ) {
fn.and = fn;
return fn;
}
Tien Dung





