Skip to content

Instantly share code, notes, and snippets.

@josher19
Created January 11, 2010 11:09
Show Gist options
  • Save josher19/274158 to your computer and use it in GitHub Desktop.
Save josher19/274158 to your computer and use it in GitHub Desktop.
// Common JavaScript error for parameter "shortcuts".
// Be careful when you do this shortcut to assign default values!
function BuggyClass(param1, param2,param3) {
this.param1 = param1 || "defaultValue"
this.param2 = param2 || true;
this.param3 = param3 || -1;
this.input = param1 + ".." + param2;
this.derived = this.param1 + ".." + this.param2;
this.same = this.derived == this.input; // should always be true, right?
}
BuggyClass.prototype.unexpected = function() {
var res = [];
for (attr in this) {
var t = typeof(this[attr]);
if (t != "function" && t != "undefined") res.push(attr + "=" + this[attr]);
}
return res.join("\n")
}
BuggyClass.prototype.toString = BuggyClass.prototype.unexpected;
var show = self.consle ? console.log : function(msg) { alert(msg); }
var bugsMeDefault = new BuggyClass(null);
// This is buggy:
var bugsme = new BuggyClass("ok", false,0);
///// May not get what you expect!!!
var results = [
bugsMeDefault,
bugsme.unexpected(),
bugsme.param1,
bugsme.param2 == false,
bugsme.param3 == 0,
].join("\n\n");
show(results);
// Questions: how do you set param2 to false in the constructor?
// Answer: not easily!!!
// See also: http://gist.github.com/274880
// How can we fix this class?
// See answers in BuggyClassFixed.js Gist
// http://gist.github.com/274169
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment