Posts

Showing posts with the label defineProperties

On Complex Getters And Setters

A common use case for getters and setters is via scalar values rather than complex data. Well, this is just a programmer mind limit since data we could set, or get, can be of course much more complex: here an example function Person() {} Person.prototype.toString = function () { return this._name + " is " + this._age; }; // the magic identity configuration object Object.defineProperty(Person.prototype, "identity", { set: function (identity) { // do something meaningful this._name = identity.name; this._age = identity.age; // store identity for the getter this._identity = identity; }, get: function () { return this._identity; } }); With above pattern we can automagically update a Person instance name and age through a single identity assignment. var me = new Person; me.identity = { name: "WebReflection", age: 33 }; alert(me); // WebReflection is 33 While the example may not make muc...

Object.prototype.define Proposal

Somebody may think that defineProperties is boring and I kinda agree on that. The good news is that JavaScript is flexible enough to let you decide how to do that ... and here I am with a simple proposal that does not hurt, but can make life easier and more intuitive in modern JS environments. Unobtrusive Object.prototype.define How To Well, the handy way you expect. The method returns the object itself, so it is possible to define one or more property runtime and chain different kind of definitions, as example splitting properties from method and protected properties from protected methods. var o = {}.define("test", "OK"); o.test; // OK Multiple properties can share same defaults: var o = {}.define(["name", "_name"], "unknown"); o.a; // unknown o._a; // unknown Methods are immutable by default and properties or methods prefixed with an underscore are by default not enumerable. function Person() {} Person.protoype.define( ["getN...

[ES5] Classes As Descriptor Objects

In my latest posts I have talked about current situation for JavaScript " Classes ". In Good Old And Common JS Errors I have introduced a misconception of a generic "Class" function which is usually not able to produce instanceof Class , considering Classes in JS are functions indeed. In Better JS Classes I have explained how to write a meaningful Class factory , avoiding the _super pollution over each extended method, while in the JS _super Bullshit I have explained why the _super/parent concept does not scale with JavaScript prototypal inheritance model. More than a dev, Mr Crockford included, agreed that in JavaScript the classical pattern does not fit/scale/produce expected results, and even worst, it could cause "disasters" during a session and slow down overall performances (and about this topic I have already said that web developers should stop to test their stuff with powerful CPU, read Macs! Buy a bloody Atom based device as I have done and af...