Functions in JavaScript

  • JavaScript doesn’t have classes in the true sense as, say, does Java. It’s all about functions.
  • Remember that functions are first-class objects in JavaScript. This means that they can have properties like any other objects. Since properties are objects and so are functions, it follows that a function can have a property that is itself a function!
  • Functions can pretend to be classes and we still use new when constructing new instances.
function Car(make, model, year) {
      this.make = make;
      this.model = model;
      this.year = year;
}

var myCar = new Car("Eagle", "Talon TSi", 1993);
var myOtherCar = new Car("Dodge", "Dart", 1971);
  • But at their core, functions are still objects. You can assign a function to a property of another object, and then invoke using () on that object’s (function) property. It follows then that functions can be passed as arguments into other functions.
  • The object Object is still the super-object of all objects in JavaScript.
  • You can dynamically add new properties (and set their values) even after you’ve constructed an object that didn’t have that property to begin with. WEIRD.
  • If a function is behaving as a class, then a property inside it that is a function will be acting as a method in Java and is therefore called a method.
  • To check if a parameter was given or not (because remember you can call a method with less or more than defined number of arguments), you use
  if (!someArg) { // ! of 'undefined' is true
    ...
  }
  • Even if a function was declared with no args it still has access to an inbuilt array of arguments if someone sends more args and this array is called ‘arguments’
function noArgs() {
   console.log(arguments.length);
}
  • A “function literal” is when you create a function and assign it to a var. e.g.
var addMe = function(){return arguments[0] + arguments[1]};
console.log(addMe(1,2)); // 3
  • A self executing anonymous function is like
(function(){return arguments[0] + arguments[1]})(1,2); // 3
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s