PHP Class
class Dog {
var $name;
function __construct($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
$fido = new Dog("Fido");
} $fido->getName(); // Fido
JS constructor function
function Dog (name) {
this.name = name;
this.getName = function () {
return this.name;
};
}
var fido = new Dog("Fido");
fido.getName();
JS constructor function
¤ Constructors are just functions
¤ Functions called with new…
¤ …return this…
¤ …implicitly.
Constructor and prototype
function Dog (name) {
this.name = name;
}
Dog.prototype.getName = function () {
return this.name;
};
var fido = new Dog("Fido");
fido.getName();
Prototypes
¤ Every function has a prototype property
¤ It’s useless, unless …
¤ … the functions is called with new.
Constructor and prototype
function Dog (name) {
this.name = name;
}
Dog.prototype.getName = function () {
return this.name;
};
var fido = new Dog("Fido");
fido.getName(); // Fido
We don’t need no constructors
¤ object literals
// yep
var o = {};
// nope
var o = new Object();
We don’t need no constructors
¤ array literals
// yep
var a = [];
// nope
var a = new Array();
We don’t need no constructors
¤ regular expression literals
// yep
var re = /[a-z]/gmi;
// proly nope
var re = new RegExp("[a-z]", "gmi");
We don’t need no constructors
¤ functions
// yep
var f = function(a, b) {return a + b;};
// yep
function f(a, b) {return a + b;}
// nope
var f = new Function("a, b",
"return a + b;");
We don’t need no constructors
¤ strings
// yep
var s = "confoo";
// nope
var s = new String("confoo");
s.substr(3); // "foo"
"confoo".substr(0, 4); // "conf"
We don’t need no constructors
¤ numbers
// yep
var n = 1.2345;
// nope
var n = new Number(1.2345);
n.toFixed(2); // 1.23
We don’t need no constructors
¤ boolean
// yep
var b = true;
// nope, why would you ever
var b = new Boolean(true);
We don’t need no constructors
¤ Errors
throw new Error("Ouch");
// but you could also
throw {
name: "MyError",
message: "Ouch"
};