Javascript Cheat Sheet

11 December 2019 Link



Conventions

  • Constructor functions define, in a sense, classes, and classes have names that begin with capital letters. Regular functions and methods have names that begin with lowercase letters.

Creating Objects

  • Method 1:
   var empty = {}; // An object with no properties
   var point = { x:0, y:0 }; // Two properties
   var point2 = { x:point.x, y:point.y+1 }; // More complex values
   var book = {
       "main title": "JavaScript", // Property names include spaces,
       'sub-title': "The Definitive Guide", // and hyphens, so use string literals
       "for": "all audiences", // for is a reserved word, so quote
       author: { // The value of this property is
           firstname: "David", // itself an object. Note that
           surname: "Flanagan" // these property names are unquoted.
       }
    };
  • Method 2
var o = new Object(); // Create an empty object: same as {}.
var a = new Array(); // Create an empty array: same as [].
var d = new Date(); // Create a Date object representing the current time
var r = new RegExp("js"); // Create a RegExp object for pattern matching.

'this' Keyword

// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
  this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;
  
// change bob's age to 50 here
bob.setAge(50);

Classes

Constructor Functions to Make Classes

function Person(name,age) {
  this.name = name;
  this.age = age;
}

// Let's make bob and susan again, using our constructor
var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 25);
// help us make george, whose name is "George Washington" and age is 275

var george = new Person("George Washington", 275);

Using custom properties as prototypes to make classes

// range.js: A class representing a range of values.
// This is a factory function that returns a new range object.
function range(from, to) {
    // Use the inherit() function to create an object that inherits from the
    // prototype object defined below. The prototype object is stored as
    // a property of this function, and defines the shared methods (behavior)
    // for all range objects.
    var r = inherit(range.methods);
    // Store the start and end points (state) of this new range object.
    // These are noninherited properties that are unique to this object.
    r.from = from;
    r.to = to;
    // Finally return the new object
    return r;
}
// This prototype object defines methods inherited by all range objects.
range.methods = {
    // Return true if x is in the range, false otherwise
    // This method works for textual and Date ranges as well as numeric.
    includes: function(x) { return this.from <= x && x <= this.to; },
    // Invoke f once for each integer in the range.
    // This method works only for numeric ranges.
    foreach: function(f) {
    for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
    },
    // Return a string representation of the range
    toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
// Here are example uses of a range object.
var r = range(1,3); // Create a range object
r.includes(2); // => true: 2 is in the range
r.foreach(console.log); // Prints 1 2 3
console.log(r); // Prints (1...3)


Prototypes

function Dog (breed) {
  this.breed = breed;
};

// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() {
  console.log("Woof");
};
buddy.bark();

// here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();

  • Defining a prototype
// original classes
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
    this.isAlive = true;
}
function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
}
function Emperor(name) {
    this.name = name;
    this.saying = "Waddle waddle";
}

// set up the prototype chain
Penguin.prototype = new Animal();
Emperor.prototype = new Penguin();

var myEmperor = new Emperor("Jules");

console.log( myEmperor.saying ); // should print "Waddle waddle"
console.log( myEmperor.numLegs ); // should print 2
console.log( myEmperor.isAlive ); // should print true

hasOwnProperty to explore prototype
// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype
console.log(prototypeType);     // object

// now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty");
console.log(hasOwn);     // true

Private Variables and Functions

function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   this.getBalance = function() {
      // your code should return the bankBalance
      return bankBalance;
   };
}

var john = new Person('John','Smith',30);
console.log(john.bankBalance);

// create a new variable myBalance that calls getBalance()
var myBalance = john.getBalance();
console.log(myBalance);

And private functions:
function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   var returnBalance = function() {
      return bankBalance;
   };
       
   // create the new function here
   this.askTeller = function(){
       return returnBalance;
   };
}

var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

Jquery


Loading Code

Running function on page load

<html>
  <head>
    <script src="/rtl/jquery.js"></script>
    <script>
$(function() {                          // Function run when the page is loaded and DOM is ready
   $("#out").empty();               // Empties the HTML element with id="out" so if javascript is enabled the user will not see the "Please enable Javascript" message
   $("#in").keypress(function(ev) {
      $("#out").append(String.fromCharCode(ev.which));
   });
});
    </script>
  </head>
  <body>
    <h1 id="out">Please enable JavaScript</h1>
    <input id="in" type="text" />
  </body>
</html>

Other method

var main = function() {

}

$(document).ready(main);           // Loads and runs the main function when the page is loaded in the browser

Referring to elements

Referring to id
$("#idname")
Referrring to class
$(".classname")

Development

Environment

  • Netbeans with Chrome is a good environment. Netbeans project can be created and the files populated in the project directory. Now when you execute it opens in chrome and you can set breakpoints in the javascript code.
  • Chrome has plenty of developer tools in the browser itself:
    • Inspect can allow you to browse the DOM structure and shows the current DOM structure which shows the page. All javascript manipulations are shown directly int he structure.
    • Console shows useful messages or error messages that happen when the Javascript code runs.
    • Network tabs hows all the network requests of the page and which ones fail and how much time each took.
  • Sometimes code is loaded dynamically from a string. To pause the debugger in that code to allow debugging in there just add debugger; statement at which the debugger will pause. This is mentioned in this question. This is the way I was finally able to explore the objects when developing a Tiddlywiki 5 Macro

Resources