I watched a talk by Douglas Crockford on the good parts in Javascript and my eyes
were opened. At one point he said, something like, "Javascript is the only language where good programmers believe they can use it effectively, without learning it." Then I realized, I am that guy.
In that talk, he made some statements that for me, were pretty surprising and insightful. For example, JavaScript is the most important programming language on the planet. Or it is the most popular language on the planet. And, that it is broken in many serious ways.
The most surprising statement he made, for me, was "new is dangerous". He doesn't use it any more. He doesn't use this
either.
He presented an interesting pattern for a constructor in Javascript, one that allows for private and public member variables, and relies on neither new
, nor this
. It looks like this:
// neo-classical constructor
var container = function(initialParam) {
var instance = {}; // empty object
// private members
var privateField_Value = 0;
var privateField_Name = "default";
var privateMethod_M1 = function (a,b,c) {
// arbitrary
};
// initialParam is optional
if (typeof initialParam !== "undefined") {
privateField_Name= initialParam;
}
// public members
instance.publicMethod = function(a, b, c) {
// because of closures,
// can call private methods or
// access private fields here.
};
instance.setValue = function(v) {
privateField_Value = v;
};
instance.toString = function(){
return "container(v='" + privateField_Value + "', n='" + privateField_Name + "')";
};
return instance;
}
// usage
var a = container("Wallaby");
WScript.echo(a.toString());
a.setValue(42);
WScript.echo(a.toString());
var b = container();
WScript.echo(b.toString());
EDIT: code updated to switch to lowercase class name.
This pattern has evolved from Crockford's earlier usage models.
Question: Do you use this kind of constructor pattern? Do you find it understandable? Do you have a better one?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…