William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Tag Archives: javascript

JavaScript UI tips

Some tips for quick retrieving:

(1) MongoDB Windows GUI

http://robomongo.org/

(2) Node-Inspector / debugger

node-inspector: debug js, supervisor

(3) AngularJS

Karma / Testacular: JavaScript Test Runner
run in MINGW32 (git bash)

(4) Promise:

then(): http://promises-aplus.github.io/promises-spec/
Q(): https://github.com/kriskowal/q
It(callback) must use an explicit try block to catch the exception that JSON.parse might throw and must manually forward all errors to the subscriber. It also must take care not to call the subscriber inside the try block, since this would catch errors thrown by nodeback and throw them back at nodeback in the catch block. In general, writing callback-based functions that handle errors robustly is difficult and error-prone, and even if you do it right, rather verbose.
The second reward for using promises is that they implicitly guarantee that interfaces you create will be strictly asynchronous.

(5) log()
function log() {
  var local = /(localhost|127.0.0.1|192.168)/.test(location.href);
  if (local || typeof console.log === 'function') {
    console.log.apply(console, arguments);
  }
}
(6) WebStorm:
1. Code Analysis
Inspect Codes...
script:src (tab)

2. Keyboard Shortcuts
shortcutfoo.com
ctrl+shift+A

3. Actions
4. Templates
save as: Live Templates

5. Refactoring
function creation:
alt+enter

6. Navigation
7. Local History / Version Control
Changes -> Log
git history

8. External Tools (appear in TOOLS tab)
adding yeoman:
- yo angular
- npm install
- bower install
- common
- controller
- directive
- filter
- main
- route
- service
- view
mingw32 terminal / command-line

9. File Watchers
Coffee Script
10. Plugins
(7) Yeoman.io

Yeoman 1.0 is more than just a tool. It’s a workflow; a collection of tools and best practices working in harmony to make developing for the web even better.

Parasitic + Combination Inheritance

JavaScript: Parasitic + Combination Inheritance

The Parasitic + Combination Inheritance which I use in my codes:

//Parasitic + Combination Inheritance
// reference:
function object(o) {
  function F(){}
  F.prototype = o;
  return new F();
}
// deal with prototype:
function inheritPrototype(child, parent) {
  function F() {}
  F.prototype = parent.prototype;
  var p = new F();
  p.constructor = child;
  child.prototype = p;
}

function Super(args) {
 //this attrs and methods
}
Super.prototype.say1 = function() {
  //process args...
}

function Sub(args, more_args) {
  //inherit Super
  //2.
  Super.call(this, args);
  this.more_arges = more_args;
}
//1.
inheritPrototype(Sub, Super);

Sub.prototype.say2 = function() {
  // process more_args;
}

These are original from Nicholas Zakas’s ‘Professional JavaScript for Web Developers (3rd Edition)’ which I refer to.

JavaScript inherit examples

JavaScript Inheritance

Here I list some basic JavaScript inheritance examples for quick retrieving. Original reference from Stoyan Stefanov. JavaScript inheritance are *NOT* as easy as PHP. I am afraid this will prevent Node.js from getting further in the server-side.

//1.Very Basicly ineritance - Copy:
function inheritCopy(C, P) {
  C.prototype = new P();
}
// function Parent(){}; function Child(){};
// inheritCopy(Child, Parent);
//Child's prototype is an instance invocation of Parent.

The Select2.js using this to do extension.

// select2.js, using jQuery.extend(), multi-inheritance:
function clazz(Parent, methods) {
    var F = function () {};
    F.prototype = new Parent;
    F.prototype.constructor = F;
    F.prototype.parent = Parent.prototype;
    F.prototype = $.extend(F.prototype, methods);
    return F;
}
// var AbstractSelect2 = clazz(Object, {...});
// var SingleSelect2 = clazz(AbstractSelect2, {...});
// var MultiSelect2 = clazz(AbstractSelect2, {...});

If not want to get copy from Parent(), just want prototype inheritance, then:

function Parent() {};
function Child(){};
Child.prototype = Parent.prototype; //reference
var c = new Child(); //get all constructors' prototype.

An advanced version which:

  1. not including Parent attrs;
  2. inerit Parent.prototype;
  3. change Child.prototype not effect Parent
// sub-constructor inherit
function extend(Child, Parent) {
  var F = function() {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}
// function Shape() {}; function TwoDShape() {};
// extend(TwoDShape, Shape);

The following inherit from an object, not from constructor function, and extends its attrs to combine in the second paramter’s hash object.

function objectMixAttrs(o, attrs) {
  var n = null;
  function F() {};
  F.prototype = o;
  n = new F();
  n.uber = o;

  for(var i in attrs) {
    n[i] = attrs[i];
  }
  return n;
}
// var fastFood = objectMixAttrs(food, { fast_hash });

A Recursive and deepCopy example:

function deepCopy(p, c) {
  var c = c || {};
  for (var i in p) {
    if(typeof p[i] === 'object') { // Array or Hash?
      c[i] = (p[i].constructor === Array) ? [] : {};
      deepCopy(p[i], c[i]);
    }
    else {
      c[i] = p[i];
    }
  }
  return c;
}
// var parent={...}; var deep = deepCopy(p);

JavaScript Inheritance examples

JavaScript Inheritance

Here I list some basic JavaScript inheritance examples for quick retrieving. Original reference from Stoyan Stefanov. JavaScript inheritance are *NOT* as easy as PHP. I am afraid this will prevent Node.js from getting further in the server-side.

//1.Very Basicly ineritance - Copy:
function inheritCopy(C, P) {
  C.prototype = new P();
}
// function Parent(){}; function Child(){};
// inheritCopy(Child, Parent); 
//Child's prototype is an instance invocation of Parent.

The Select2.js using this to do extension.

// select2.js, using jQuery.extend(), multi-inheritance:
function clazz(Parent, methods) {
    var F = function () {};
    F.prototype = new Parent;
    F.prototype.constructor = F;
    F.prototype.parent = Parent.prototype;
    F.prototype = $.extend(F.prototype, methods);
    return F;
}
// var AbstractSelect2 = clazz(Object, {...});
// var SingleSelect2 = clazz(AbstractSelect2, {...});
// var MultiSelect2 = clazz(AbstractSelect2, {...});

If not want to get copy from Parent(), just want prototype inheritance, then:

function Parent() {};
function Child(){};
Child.prototype = Parent.prototype; //reference
var c = new Child(); //get all constructors' prototype.

An advanced version which:

  1. not including Parent attrs;
  2. inerit Parent.prototype;
  3. change Child.prototype not effect Parent
// sub-constructor inherit
function extend(Child, Parent) {
  var F = function() {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}
// function Shape() {}; function TwoDShape() {};
// extend(TwoDShape, Shape);

The following inherit from an object, not from constructor function, and extends its attrs to combine in the second paramter’s hash object.

function objectMixAttrs(o, attrs) {
  var n = null;
  function F() {};
  F.prototype = o;
  n = new F();
  n.uber = o;
  
  for(var i in attrs) {
    n[i] = attrs[i];
  }
  return n;
}
// var fastFood = objectMixAttrs(food, { fast_hash });

A Recursive and deepCopy example:

function deepCopy(p, c) {
  var c = c || {};
  for (var i in p) {
    if(typeof p[i] === 'object') { // Array or Hash?
      c[i] = (p[i].constructor === Array) ? [] : {};
      deepCopy(p[i], c[i]);
    }
    else {
      c[i] = p[i];
    }
  }
  return c;
}
// var parent={...}; var deep = deepCopy(p);

JavaScript: Factory Pattern

JavaScript: Factory Pattern

The following is a typical Factory pattern for JavaScript, original from Stoyan Stefanov.

 //1. constructor:
function CarMaker() {}

//2. Factory Items Iteration:
CarMaker.Compact = function(){};
CarMaker.Convertible = function(){};
CarMaker.SUV = function() {};

//3. public methods:
CarMaker.prototype.tool = function() {};
CarMaker.prototype.drive = function() {};

//4. Static methods:
CarMaker.factory = function(type) {
  var constr = type;

  if(typeof CarMaker[constr] !== 'function') {
     throw {
       name: "Error",
       message: constr + 'not exist'
     };
  }
  //inheritance only once
  if(typeof CarMaker[constr].prototype.tool !== 'function') {
    CarMaker[constr].prototype = new CarMaker();
  }

  return new CarMaker[constr]();
}

//5. Usage:
var camry = CarMaker.factory('Convertible');
var cherokee = CarMaker.factory('SUV');
camry.tool();
cherokee.drive(); 

JavaScript: Factory Pattern

JavaScript: Factory Pattern

The following is a typical Factory pattern for JavaScript, original from Stoyan Stefanov.

 //1. constructor:
function CarMaker() {}

//2. Factory Items Iteration:
CarMaker.Compact = function(){};
CarMaker.Convertible = function(){};
CarMaker.SUV = function() {};

//3. public methods:
CarMaker.prototype.tool = function() {};
CarMaker.prototype.drive = function() {};

//4. Static methods:
CarMaker.factory = function(type) {
  var constr = type;
  
  if(typeof CarMaker[constr] !== 'function') {
     throw {
       name: "Error",
       message: constr + 'not exist'
     };
  }
  //inheritance only once
  if(typeof CarMaker[constr].prototype.tool !== 'function') {
    CarMaker[constr].prototype = new CarMaker();
  }
  
  return new CarMaker[constr]();
} 

//5. Usage:
var camry = CarMaker.factory('Convertible');
var cherokee = CarMaker.factory('SUV');
camry.tool();
cherokee.drive(); 

JavaScript constructor function: public,private,privileged,static method

JavaScript constructor function: public,private,privileged,static method

The following includes various JavaScript methods for a constructor function:

  1. public method – prototype
  2. privileged method – function method with this
  3. private method – closure method without this
  4. Public static method
function Person(name) {
  this.name = name || "public";
  // 1. privileged
  this.getName = function() {
    return this.name + ', ' + privateMethod();
  }
  // 2. private
  var privates = 'private';
  function privateMethod() {
    return privates;
  }
}

// Public methods
Person.prototype = {
	getDate: function() {
		return new Date();
	},
	getWorld: function(){
		return this.name;
	}
}

// Public Static method:
Person.act = function() {
  return Person.constructor.prototype.constructor;
}

var p = new Person();
p.getName('william Jiang');
p.getDate();
p.getWorld();
Person.act();

JavaScript constructor function: public,private,privileged,static method

JavaScript constructor function: public,private,privileged,static method

The following includes various JavaScript methods for a constructor function:

  1. public method – prototype
  2. privileged method – function method with this
  3. private method – closure method without this
  4. Public static method
function Person(name) {
  this.name = name || "public";
  // 1. privileged
  this.getName = function() {
    return this.name + ', ' + privateMethod();
  }
  // 2. private
  var privates = 'private';
  function privateMethod() {
    return privates;
  }
}

// Public methods
Person.prototype = {
	getDate: function() {
		return new Date();
	},
	getWorld: function(){
		return this.name;
	}
}

// Public Static method:
Person.act = function() {
  return Person.constructor.prototype.constructor;
}

var p = new Person();
p.getName('william Jiang');
p.getDate();
p.getWorld();
Person.act();

JavaScript: Empty Object Comparison

JavaScript: Empty Object Comparison

The following is my summary of empty object comparsion. They used in node command line.
They are slightly difference. For prototype inheritance, always use var o={};

var o; //undefined var o=null; //for empty object var o={}; //distinct a object
var o; var o=null; var o = {};
o.__proto__; //Error o.__proto__; //Error o.__proto__; // {}
o.constructor; //Error o.constructor; //Error o.constructor; // [Function: Object]
o.instanceof Object; //false o.instanceof Object; //false; o instanceof Object; // true
typeof o; //’undefined’ typeof t; //’object’ typeof o; // ‘object’
o; //undefined o; //null o; //{}
o.length; // Error o.length; //Error o.length; //undefined
o.toString(); //Error o.toString(); //Error o.toString(); //[object Object]

JavaScript: Empty Object Comparison

JavaScript: Empty Object Comparison

The following is my summary of empty object comparsion. They used in node command line.
They are slightly difference. For prototype inheritance, always use var o={};

var o; //undefined var o=null; //for empty object var o={}; //distinct a object
var o; var o=null; var o = {};
o.__proto__; //Error o.__proto__; //Error o.__proto__; // {}
o.constructor; //Error o.constructor; //Error o.constructor; // [Function: Object]
o.instanceof Object; //false o.instanceof Object; //false; o instanceof Object; // true
typeof o; //’undefined’ typeof t; //’object’ typeof o; // ‘object’
o; //undefined o; //null o; //{}
o.length; // Error o.length; //Error o.length; //undefined
o.toString(); //Error o.toString(); //Error o.toString(); //[object Object]