JavaScript Quick Tips #4

08/16/2013, Fri
Categories: #JavaScript
Tags: #jQuery

Prototype and This

When attaching a method onto a prototype, the methods can be called from another prototype method using "this".

// Use this for Prototype functions
var myObject = function () {};

myObject.prototype.myMethod = function () {
  console.log("executed myMethod");
};

myObject.prototype.anotherMethod = function () {
  // no need to run myObject.prototype.myMethod()
  // to execute myMethod, but use "this" instead
  this.myMethod();
};

// same concept applies here
myObject.anotherMethod();

Function Arguments

If your function takes in many arguments, it might be more easy to follow when the parameters are broken up to multiple lines.

// Breaking up Function Parameters

var here = "here",
  is = "is",
  an = "an",
  example = "example",
  that = "that",
  shows = "shows",
  lines = "lines",
  broken = "broken",
  up = "up";

function coolFunction(here, is, an, example, that, shows, lines, broken, up) {
  // also works for logging
  console.log(
    [here, is, an, example, that, shows, lines, broken, up].join(" ")
  );
}

coolFunction(here, is, an, example, that, shows, lines, broken, up);