Tuesday, May 6, 2008

Fun with JavaScript Chainability

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 (i = 0; i < l; i+=1) {
fn(a[i]);
}
end

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;
}

2 comments:

HoàngKC said...

Khi dùng phương thức "and" mà gọi đến đối tượng thứ 2 trở đi, có phải hàm "addAndMagicTo" trở nên thừa không anh? Vì phương thức "and" đã tồn tại rồi

Mà theo em thấy, hàm forEach của anh, nếu đổi fn làm tham số đầu tiên và sau đó "call" hoặc "apply" cho các tham số tiếp theo thì sẽ rất tiện, không nhất thiết phải dùng array, và đặc biệt còn có lợi khi dùng trong OOP (để trỏ lại con trỏ this)

btw, còn nhớ em là ai không nhỉ :P

Alex Nguyen said...

Đúng là thừa "and" thật. Anh viết "addAndMagicTo" cho vui và để demo tính mềm dẻo của JavaScript object (function is the first class object) nên không nghĩ xa. Hi hi. Nên gọi "addAndMagicTo" ở ngoài function chính thì hợp lý hơn.

Còn hàm "forEach" anh muốn demo chân phương hàm "map" cho một mảng. Gợi ý của em rất hay.

Còn nhớ em là ai không nhỉ :p Hi hi, anh chịu :p

Cám ơn em đã comment ...