Implementing The Core MOPA Methods Part 1
A full implementation of Morphtron provides a common, transparent means of providing access to properties by using the native property if it exists. In cases where no native property exists, MOPA methods then use or optionally create an accessory. For example consider this Smalltalk(Squeak and Dolphin) implementation of fetchProperty:
fetchProperty: aSymbol
| property |
property _ self fetchNativeProperty: aSymbol.
property
ifNotNil: [^ property].
^ self fetchAccessory: aSymbol
The details of fetchNativeProperty are left up to the implementor. She can determine what access to native properties will be allowed. The following Smalltalk implementation this:
fetchNativeProperty: aSymbol
| ivarValue |
(self class allInstVarNames includes: aSymbol)
ifTrue: [”aSymbol is an ivar”
(self isPrivateInstVar: aSymbol)
ifFalse: [”aSymbol has not been declared private”
(self class lookupSelector: aSymbol) isNil
ifTrue: [self allowInstanceVariablePropertiesWithoutAccessors
ifTrue: [ivarValue _ Compiler
evaluate: ‘^’ , aSymbol asString
for: self
logged: false]]
ifFalse: [ivarValue _ self perform: aSymbol]]].
^ ivarValue
Now for a prototype-based language such as Javascript, things are simplified because all properties are native:
function fetchProperty(aName) {
/*
Using fetchProperty for accessing properties has a number of different benefits. It is easier for beginner-to-intermediate programmers and allows Morphtron behaviors to be ported between different object environments. It also lets accessories be used transparently as properties. That said, a programmer with sufficient knowledge can still use built-in properties and accessories however she wants. See also fetchAccessory. One interesting use of accessories is for undo.
*/
var theProperty=this[aName];
if(typeof(theProperty)==’undefined’) {
theProperty=this.fetchAccessory(aName);
}
return(theProperty);
}