Javascript is nothing but ODD
“Javascript” is nothing but Object Definition & Destruction. This is not something new. When you say, everything is object in Javascript we are not talking about two different things here. By saying ODD, we are celebrating the distinct nature of the language. Like I always say, it has it’s own taste and smell. This is why the nerds and the fellow developers say it’s Simple & Powerful. I don’t stop you calling it your way, and you can’t resist either too!
I recently wrote and published a simple npm package called inscriber. This allows you to configure computed properties inside the object. The scope is restricted to object so you can manage it better. If needed, you can extend this to your application scope as well. As we all know about computed properties this needs no further explanation. For naive coders, the examples below will help!
Example: Consider A Simple Javascript Object `Person`person: {
firstName: 'David',
lastName : 'Field',
fullName : 'David Field'
}Explanation: In person object, `firstName` & `lastName` are properties, which holds value to identify the person. But, `fullName` doesn't hold any value by itself nor it consider to hold. It's something which is calculated / computed from the former properties. So in javascript it can be written as a method or compute property to perform this operation
Let’s just look at the computation of fullName
here. It’s going to do only two things at any given point of time. a) Compose fullName
b) firstName
or lastName
is changed, recompose fullName
This can be simply ported into Javascript in three steps: Object
, Definition
& Destruction
Object
— Holds the value & operations togetherDefinition
— Empowers the watch capabilityDestruction
— Facilitates the re-definition
- Object Representation
// `Person` Object in Javascript
person: {
firstName: 'Donald',
lastName : 'Trump',
fullName : function() {
return `${this.firstName} ${this.lastName}`;
}
}
2) Property Definition
// Flag confirms change in binding properties of `fullName`
var fullNameChanged = false;// Add watch to properties like `firstName` & `lastName`
var value = person['propName'];
Object.defineProperty(person, 'propName', {
get: function() {
return value;
},
set: function(propValue) {
this['propName'] = propValue;
fullNameChanged = true;
}
});// Definition of computed property `fullName`
Object.defineProperty(person, 'fullName', {
get: function() {
return this.getFullName();
}
});// Computation of `fullName` from binding properties
function getFullName() {
return `${this.firstName} ${this.lastName}`;
};
3) Object Destruction
// Destruction of `fullName`
var fullName = person.fullName;
delete person.fullName;
person.fullName = fullName
Thank You!