Javascript objects
Javascript objects
See here
var obj = {}; //same as = new Object(); var arr = []; //same as = new Array(); //initialize if does not exist (defined in another js file?) window.myNamespace = window.myNamespace || {}; //object literal var person = { name: "Martin", //use : not = and append the comma toString: function() { return "I am " + this.name; } }; //anonymous functions can auto-execute (function() { var name = document.getElementById("text").value; function copy() { document.getElementById("out").value = name; } copy(); }()); //(immediately invoked function expression -IIFE/"iffy") //revealing module pattern var revealingModulePattern = function(){ function privateCopy() { } //not in object notation function willBePublicCopy() { } return { //return an anonyomous object publicVar: willBePublicCopy() //alias what you make public } }();
Javascript object detection
In javascript, an object that isn't defined is actually undefined, not null. The following show the different checks which will indicate whether a top level object exists. Note top-level global objects are actually properties of the window (self) object and you usually need to specify it (otherwise it unhelpfully throws an exception because it's undefined).
//only form to not need self. if (typeof (MayNotExist) != "undefined") MayNotExist += 1; //weak checking against null if (self.MayNotExist != null) MayNotExist += 1; //strong checking undefined if (self.MayNotExist !== undefined) MayNotExist += 1; //simple if (self.MayNotExist) MayNotExist += 1;
this, prototypes and constructors
A constructor is a normal function with optional arguments and typically properties (incl. methods) assigned to this
//a function that is a constructor var person = function (name) { //the properties (and methods) are given object scope with this this.name = name; }; //"new" makes an object instance var p = new person(); console.log(p.constructor.toString()); //this is the ctor function
Use .prototype for shared functions or inheritance.
person.prototype = { changeName: function (name) { this.name = name; } }; var ninja = function () {}; ninja.prototype = new person(); var p = new ninja("John");
If you don't "new" an object, "this" means the global window object. And in event handlers, depending how they are assigned, "this" may be the window object or the element that invoked them. You can override with method.call(context) (or .apply)
var Feline = function (name) { this.name = name; }; var Cat = function (name, stripes) { //call chaining Feline.call(this, name); this.stripes = stripes; }; Cat.prototype = new Feline(); var cat = new Cat("tigger", true);
NB: nested functions also lose the context.
var Adder = function (x, y) { this.x = x; this.y = y; this.sum = function () { var calc = function () { //here's an inner function - "this"=="window"!! return this.x + this.y; }; //so we have to pass this down return calc.call(this); }; };