30. PHP Class
class Dog {
var $name;
function construct($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
$fido = new Dog("Fido");
} $fido->getName(); // Fido
31. JS constructor function
function Dog (name) {
this.name = name;
this.getName = function () {
return this.name;
};
}
var fido = new Dog("Fido");
fido.getName();
32. JS constructor function
Constructors are just functions
Functions called with new…
…return this…
…implicitly.
33. Constructor and prototype
function Dog (name) {
this.name = name;
}
Dog.prototype.getName = function () {
return this.name;
};
var fido = new Dog("Fido");
fido.getName();
34. Prototypes
Every function has a prototype property
It’s useless, unless …
… the functions is called with new.
35. Constructor and prototype
function Dog (name) {
this.name = name;
}
Dog.prototype.getName = function () {
return this.name;
};
var fido = new Dog("Fido");
fido.getName(); // Fido
51. We don’t need no constructors
object literals
// yep
var o = {};
// nope
var o = new Object();
52. We don’t need no constructors
array literals
// yep
var a = [];
// nope
var a = new Array();
53. We don’t need no constructors
regular expression literals
// yep
var re = /[a-z]/gmi;
// proly nope
var re = new RegExp("[a-z]", "gmi");
54. 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;");
55. 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"
56. We don’t need no constructors
numbers
// yep
var n = 1.2345;
// nope
var n = new Number(1.2345);
n.toFixed(2); // 1.23
57. We don’t need no constructors
boolean
// yep
var b = true;
// nope, why would you ever
var b = new Boolean(true);
58. We don’t need no constructors
Errors
throw new Error("Ouch");
// but you could also
throw {
name: "MyError",
message: "Ouch"
};