Just saw Douglas Crockfords talk at Craft Conference
http://www.ustream.tv/recorded/46640057
Just tried it and must say, it has a certain beauty in it.
No tangeling with prototypes and this/that fuckup.
var Animal = function(name, legs) {
legs = legs || 4;
function toString() {
return JSON.stringify({
name: name,
legs: legs
});
},
// Public API
return Object.freeze({
toString: toString,
get name() { return name },
get legs() { return legs },
set legs(newLegs) { legs = newLegs }
});
}
var Dog = function(name, owner) {
animal = Animal(name, 4);
function toString() {
return JSON.stringify({
name: name,
owner: owner,
legs: animal.legs
});
}
function bark(sound) {
return animal.name + ' ' + (sound || 'bark') + 's!';
}
// Public API
return Object.freeze({
bark: bark,
toString: toString,
get name() { return animal.name },
get legs() { return animal.legs },
});
}
var foo = Animal('Bruno');
console.log(foo.name);
console.log(foo.toString());
// objects functions can't be changed
foo.toString = function() {
return 'P4WN3D';
};
console.log(foo.toString());
var dolly = Dog('Dolly', 'Harry');
console.log(dolly.bark());
console.log(dolly.bark('waff'));
console.log(dolly.legs);
console.log(dolly.toString());