I'm a fan of a pattern that I guess we're all calling "Crockford Classless". The pattern works in all browsers and all environments, regardless of the available library, it allows strict mode to be defined in the function itself without having to re-define it all the time and offers the developer privacy in objects. It also removes the requirement of the new
keyword as the function creates an instance whether new
is used or not.
Here's a basic example of a Person
"class" created using "Crockford Classless" and "psuedo-classical" to demonstrate the two styles:
// Pseudo-classical
var PersonA = function (details) {
'use strict';
this.firstname = details.firstname;
this.lastname = details.lastname;
};
PersonA.prototype.getFullName = function () {
'use strict';
return this.firstname + ' ' + this.lastname;
};
// Creating an instance using Pseudo-classical
var person1 = new PersonA({firstname: 'John', lastname: 'Smith'}),
person2 = new PersonA({firstname: 'Fred', lastname: 'Bloggs'});
person1.getFullName(); // -> "John Smith"
person2.getFullName(); // -> "Fred Bloggs"
// Crockford Classless
function PersonB(details) {
'use strict';
var firstname = details.firstname,
lastname = details.lastname;
function getFullName() {
return firstname + ' ' + lastname;
}
return {
firstname: firstname,
lastname: lastname,
getFullName: getFullName
}
}
// Creating an instance using Crockford Classless
var person3 = PersonB({firstname: 'Max', lastname: 'Power'}),
person4 = new PersonB({firstname: 'Something', lastname: 'Witty'});
person3.getFullName(); // -> "Max Power"
person4.getFullName(); // -> "Something Witty"
Despite the advantages of "Crockford Classless", the pattern is almost universally despised with the main reason being that the methods are recreated each time. Seasoned programmers assure me that this is a waste of memory and I'm hard-pressed to deny them (they are correct, after all). Douglas Crockford defends the pattern saying that memory is so cheap these days and all devices have so much that worrying about the memory is a waste of time (something far more valuable).
My question is: how much more expensive is the the classless pattern compared to the pseudo-classical? How much more memory would I comsume if I created 10, 100 or 1000 instances of PersonB
instead of PersonA
? Does the number of methods created significantly affect the results? I see a lot of results on Google that say this is the case, but no-one seems to be able to say how severe (or trivial) the difference is.
Aucun commentaire:
Enregistrer un commentaire