i in mist of reading addy osmani's javascript design patterns can found here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/.
i finding quite enjoyable , helpful. have question 1 of patterns in book, namely command pattern.
in book, addy explains command pattern helpful decouple objects , method calls little better.
here version of example:
var person = { sayname: function (name) { return "my name " + name; }, sayage: function (age) { return "my age " + age; }, saygender: function (gender) { return "my gender " + gender; } } person.execute = function (name) { return person[name] && person[name].apply(person, [].slice.call(arguments, 1)); } console.log(person.execute("sayname", "sethen")); the magic done in execute method. can see, pass method name , arguments , method takes care of rest.
my confusion stems execute method returning. when @ it, looks short circuit && thought returned boolean due javascript conversion.
however, if try code works should, logging my name sethen.
furthermore, i've found using return person[name].apply(person, [].slice.call(arguments, 1); produces same results , in mind easier read.
so, question how return works in original execute method:
return person[name] && person[name].apply(person, [].slice.call(arguments, 1)); and how && operator works in instance make work??
the && operator not return boolean. returns value of last subexpression evaluates. if requested method name exists, expression return result of .apply() call.
so:
return person[name] && person[name].apply(person, [].slice.call(arguments, 1)); means:
if (!person[name]) return person[name]; return person[name].apply(person, [].slice.call(arguments, 1));
Comments
Post a Comment