Editing JavaScript/Notes/Factory
Jump to navigation
Jump to search
The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.
Latest revision | Your text | ||
Line 372: | Line 372: | ||
==== Be Smart, not Clever ==== | ==== Be Smart, not Clever ==== | ||
By using a <code>config</code> parameter object, we can define a parameter list of two, thereby avoiding the need for the clever <code>newApply</code> trick. | By using a <code>config</code> parameter object, we can define a parameter list of two, thereby avoiding the need for the clever <code>newApply</code> trick. | ||
=== Solution I: Create an Abstract Factory and Pass in the Constructor === | |||
<source lang="javascript"> | |||
// Create a factory. | |||
var ElementWrapperFactory = makeFactory(function() { | |||
function ElementWrapper (id, x, y) { | |||
this.id = id; | |||
this.x = x; | |||
this.y = y; | |||
this.show = _show; | |||
} | |||
function _show() { | |||
document.getElementById(this.id).style.visibility = "visible"; | |||
} | |||
return ElementWrapper; | |||
}() | |||
); | |||
// Abstract Factory, or "Factory Factory". | |||
function makeFactory(ctor) { | |||
var instances = {}; | |||
return { | |||
getById : function(id) { | |||
return instances[id] || (instances[id] = newApply(ctor, arguments)); | |||
} | |||
}; | |||
} | |||
// Implementation, or usage. | |||
var ew = ElementWrapperFactory.getById("globalWrapper", 1, 2); | |||
alert(ew.x); // 1. | |||
</source> | |||
=== Solution II: Replace ArgumentList with Parameter Object === | === Solution II: Replace ArgumentList with Parameter Object === |