ECMAScript 5:

The Definitive Slides

David Flanagan

http://davidflanagan.com

david@davidflanagan.com

Overview of ES5

Array Methods

Function.prototype.bind()

Binds a function to an object, and also does partial application.

Function.prototype.bind = function(o) {
    // Save the this and arguments values
    var self = this, boundArgs = arguments;
    return function() {
        // Build up an argument list
        var args = [], i;
        for(i = 1; i < boundArgs.length; i++)
            args.push(boundArgs[i]);
        for(i = 0; i < arguments.length; i++)
            args.push(arguments[i]);
        // Now invoke self as a method of o
        return self.apply(o, args);
    };
};

JSON

Object.create()

Object.getPrototypeOf()

Object.keys()

Object.getOwnPropertyNames()

Other New APIs

Getters and Setters

Property Attributes

Attribute Meanings

Property Descriptor

An object that describes (but does not name) a property:

var pi_descriptor = {
  value: 3.14,
  enumerable: true,
  writable: false,
  configurable: true
};
var timestamp_descriptor = {
  enumerable: true, configurable: false,   
  get: function() { 
    (new Date()).toISOString();
  },
  set: undefined
};

Working with Descriptors

Example 1

var serialnum = Object.create(Object.prototype, {
  $n: {
    value: 0,
    writable: true,
    enumerable:false,
    configurable:false
  },  
  next: {
    enumerable:true,
    configurable:true,
    get: function() { return this.$n++; },
    set: undefined
  }
});

Example 2

function copyprops(f, t) {
  var names = Object.getOwnPropertyNames(f);
  names.forEach(function(n) {
    if (n in t) return;
    var d = Object.getOwnPropertyDescriptor(f,n);
    Object.defineProperty(t, n, d)
  });
}

Example 3

// Add an Object method that doesn't 
// affect for/in loops
Object.defineProperty(
    Object.prototype,
    "extend",
    {
        enumerable: false,
        writable: true,
        configurable: true,
        value: function(from) {
            copyprops(from, this);
        }
    }
);

Example 4

// Define a class C with a superclass S.
// Give it a method m and a constant N.
function C() {}
C.prototype = Object.create(S.prototype, {
    m: {
        enumerable:false,
        writable:true,
        configurable: true,
        value: function() { /* method body */ }
    }
});
Object.defineProperty(C, "N", {
    enumerable: true,
    configurable:false, writable:false,
    value: 1
});

Object Extensibility

Lock Down

Strict Mode

"use strict";

Strict Code runs in Strict Mode

Important Strict Mode Changes

Other Strict Mode Changes

Testing For Strict Mode

// Are we in strict mode?
var strict = (function() {
    return !this; 
}());

// Is strict mode supported?
var hasstrict = (function() {
    "use strict";
    return !this;
}());

Important eval() Change

Miscellaneous Changes

For More Information