A shockingly high level of JavaScript engineers neglect to completely comprehend, and along these lines to completely use, the highlights of prototypal legacy.
Here's a basic case. Consider this code:
BaseObject = function(name) {
if(typeof name !== "undefined") {
this.name = name;
} else {
this.name = 'default'
}
};
Appears to be genuinely direct. In the event that you give a name, utilize it, generally set the name to 'default'; e.g.:var firstObj = new BaseObject();
var secondObj = new BaseObject('unique');
console.log(firstObj.name); // -> Results in 'default'
console.log(secondObj.name); // -> Results in 'unique'
Be that as it may, consider the possibility that we were.delete secondObj.name;
We'd then get:
console.log(secondObj.name); // -> Results in 'undefined'
Be that as it may, wouldn't it be more pleasant for this to return to 'default'? This should effortlessly be possible, in the event that we change the first code to use prototypal legacy, as takes after:
BaseObject = function (name) {
if(typeof name !== "undefined") {
this.name = name;
}
};
BaseObject.prototype.name = 'default';
With this adaptation, BaseObject acquires the name property from its model question, where it is set (as a matter of course) to 'default'. In this manner, if the constructor is called without a name, the name will default to default. What's more, correspondingly, if the name property is expelled from an occasion of BaseObject, the model chain will then be looked and the name property will be recovered from the model protest where its esteem is still 'default'. So now we get:var thirdObj = new BaseObject('unique');
console.log(thirdObj.name); // -> Results in 'unique'
delete thirdObj.name;
console.log(thirdObj.name); // -> Results in 'default'
0 comments:
Post a Comment