SlideShare a Scribd company logo
Insights into Javascript
  Some things you should probably know
Play along...
firebug console is your friend




    We’ll use console.log(...) a lot
Native data types...
boolean
               number
                string
              undefined

var b = true;
var s = “hello”;
var n = 45;
typeof h == ‘undefined‘ // true
s.length          // 5
Everything else is an
       Object
All objects have properties.
         you can make them anytime.
// Custom Objects
var obj = new Object();
obj[‘name’] = ‘Kurt’;
obj[true] = 45;
obj[1138] = ‘trooper’;

// Builtin Objects
var d = new Date();
var a = new Array(1,2,3);
var rx = new RegExp(/^perl$/);
This works with any object.
          Including built-ins.


var now = new Date();
now[5] = ‘hello’;
console.log(now[5]); // ‘hello’
Accessing objects has 2 flavors.
    Nearly everything in javascript is mutable!



obj[‘thing’] = ‘a’
// is the same as ...
obj.thing = ‘a’

console.log(obj[‘thing’]); // ‘a’
console.log(obj.thing); // ‘a’
{ Scope! }
not the mouthwash
3 Kinds of Scope

★ Global (in a browser it’s ‘window’)
★ Local (or Function)
★ Eval (same as local)
Scoping examples...
var a = 4;        // global scope
function fn(a) {   // local scope
  return (a + 2);
}
console.log(fn(a)); // = 6
console.log(a);      // = 4
console.log(window.a); // = 4

var p = ‘a’;
function prefix(s) {
  // p has local scope in eval
  var p = ‘pre_’;
  eval(“var ps = p + s;”); // bad, usually no need
  return ps;
}
console.log(p);     // ‘a’
Managing scope using
               Namespaces.
function foo() { /*...*/ }

// Namespace, don’t step on global ‘foo()’
var Util = {};
Util.foo = function() {
   // do stuff
}

Util.sub = {};   // nested namespaces
Util.sub.bar = 1138;
Other idioms...
What’s (in) that object?
// define an object...
var n = {
   fn: function() { },
    a: 5
};
console.log(typeof n);   // ‘object’
console.log((n instanceof Object));
// true

for (prop in n) {
  if (n.hasOwnProperty(prop)) {
    console.log('[' + (typeof n[prop])
              + '] ' + prop);
  }
}
Functions() {
that’s all you need, really.   }
What can’t you do with functions?
// functions with arguments
function add(a,b) {
  return a + b;
}
sum = add(2,2); // sum = 4

// Same as this (ref to anonymous function)
var add = function(a,b) {
   return a + b;
}
sum = add(2,2); // sum = 4

// Call it now! (immediate anonymous functions)!
var sum = (function(a,b){ return a+b; })(2,2);
// sum = 4
Function Idioms in Javascript
     This is SO common, you really need to understand it.

// functions returning functions!?,... wtf?!
var inc = (function() {
    var i = 0;
    return function() {
       return i++;
    }
})();
// anonymous function creates closed scope
console.log(inc()); // <= 0
console.log(inc()); // <= 1


           This is called a closure, more later...
More Function Idioms
// Variable arguments and ‘arguments’
function show() {
   for (var i=0; i < arguments.length; i++) {
      console.log(arguments[i]);
   }
}
// prints each argument
show(1,'cat',function(){}); // 1,‘cat’, function()

// functions are still objects
console.log('show.name = ' + show.name);
console.log('show.length = ' + show.length);
// Can’t reassign to name or length
show.prototype.name = 'cow';
console.log('show.name = ' + show.name);
Gaining closure on closures...
★ closures are the locally scoped variables in a
   function, kept around after the returned function
   goes out of scope
★ The returned function references the locally
   scoped variables, so the garbage collector retains
   the references to them.
★ the closure variables are only accessible to the
   returned function (private parts)
★ We’ll revisit this later talking about objects and
   inheritance.
new Making(Objects)
3 Object Creation Patterns
            All of these create new object instances

// Using the builtin Object
var obj = new Object();
// Object.create not always supported
var obj = Object.create(obj);

// via a Constructor
function Obj() {};
var obj = new Obj();

// Literal objects
var obj = { /* .... */ }
Constructors and new.
      Javascript is a classless language, but we can fake it.
// Constructor function (a class)
function Person(nm) {
   this.name = nm || ‘’;
}

// new instance of Person
var me = new Person(‘Dave’);
new Person(‘Aish’);    // this == window

console.log(window.name);            // ‘Aish’

console.log(me.name);      // ‘Dave’
console.log(me.constructor); // Person
Objects can’t do much without
             methods.
function Person(s) {
  this.name = s || ‘’;
}
Person.prototype.hello = function() {
  return ‘Hi, my name is ‘ + this.name;
}

var me = new Person(‘Dave’);

console.log(me.hello());
// = ‘Hi, my name is Dave’
Wait, what was that ‘prototype’
           thingy?
★ All objects have a prototype (except object
   literals)
★ the prototype contains an object that the
   container object is based on (similar to
   inheritance)
★ Containing object has all the methods &
   properties of prototype through prototype chain;
   and that prototype’s prototype, ad infinitum...
★ All newly created objects, by default, have the
   builtin Object as their prototype.
The prototype chain
★ Functions are objects, and all functions have a
   prototype property (even some native types).
★ The prototype property refers to the object that
   will be assigned as the prototype to all instances
   created when this function is used as a
   constructor.
★ Accessing a member/method follows the chain:
  ★   your object instance (this)

  ★   your object’s prototype object

  ★   your object’s prototype’s prototype

  ★   and so on ...
Modifying prototype later...
function Person(s) {
  this.name = s || ‘’;
}
Person.prototype.hello = function() {
  return ‘Hi, my name is ‘ + this.name;
}

var me = new Person(‘Dave’);
me.hello(); // = ‘Hi, my name is Dave’

Person.prototype.hello = function() {
  return ‘Hola, me llamo es ‘ + this.name;
}
var you = new Person(‘Kurt’);
you.hello(); // = ‘Hola, me llamo es Kurt’
me.hello();  // = ‘Hola, me llamo es Dave’
// Create a global object constructor
function User(name, age) {
   this.name = name; // public
   this.age = age;
   var id = null;  // private

  // Private method
  function genId() {
     return (User.idSeed++)+1000;
  }
  id = genId();
  // Privileged method
  this.getId = function() { return id; }
}
User.idSeed = 1; // static member

// Public methods (added to prototype)
User.prototype = {
   getName: function() { return this.name; },
   setName: function(nm) { this.name = nm; }
}

var emp = new User("Dave", 35);    // 2 new instances
var emp2 = new User("Francis", 40);
console.log(emp.getId());      // 1001
console.log(emp2.getId());      // 1002
Additional Notes on Previous Code

  ★ private variables can only be accessed by the
     constructor or privileged methods (due to
     closure)
  ★ public methods should always be defined in the
     object’s prototype: it’s faster and saves memory
  ★ this always refers to the invoking object (which can
     be hacked using .call() or .apply(), e.g.
    ★ User.getName.call(window, ‘Bob’), or
    ★ User.getName.apply(window, [ ‘Bob’])
Object Inheritance
 No one really likes children.
Prototypal Inheritance
                            (nearly)
// Parent ‘class’
var Person = function(s) {
   this.name = s || 'n/a';
}
// Child ‘class’ (inherits from Person)
var Employee = function(s,t) {
   this.title = t || "code monkey";
}
Employee.prototype = new Person();

var e = new Employee('Jim Relling', 'Java Master');

console.log((e instanceof Employee)); // true
console.log((e instanceof Person)); // true

console.log(e.name); // ‘n/a’
Why nearly?

★ (1) When assigning a new Person object as the
  prototype for Employee, Employee objects don’t
  get their own local copy of the prototype’s
  properties. This means:
  ★ e.name isn’t set, we get the default for the prototype
     object’s constructor.

  ★ our new Employee object doesn’t properly execute any
     code that SHOULD have been executed in it’s parent
     constructor.
Why nearly?
★ (2) Informationally, Employee’s constructor is
   incorrect and will report ‘Person’ instead.

   emp.constructor.name;    // ‘Person’
   emp.constructor === Person; // true

  ★ this is for the most part just informational; however, some
     libraries and browsers might use the constructor
     property in edge cases.

  ★ plus, semantically and logically, the constructor for an
     object should be associated with the Function that
     constructed it, e.g.

     emp.constructor.name == ‘Employee’; // yes!
Prototypal Inheritance
                     (issues corrected)
// Parent ‘class’
var Person = function(s) {
   this.name = s || 'n/a';
}
// Child ‘class’ (inherits from Person)
var Employee = function(s,t) {
   Person.call(this, s);             // (1)
   this.title = t || "code monkey";
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee; // (2)

var e = new Employee('Jim Relling', 'Java Master');

console.log((e instanceof Employee)); // true
console.log((e instanceof Person)); // true
Prototypal Inheritance
                       wrap it all up
var inherit = (function () {
    var F = function () {};
    return function (C, P) {
       F.prototype = P.prototype;
       C.prototype = new F();
       C.base = P.prototype;
       C.prototype.constructor = C;
    }
}());

function Parent() { /*...*/ }
function Child() {
   Child.base.constructor.apply(this, arguments);
   // ...
}
inherit(Child, Parent);
Questions &
Attempted Answers
        ?

More Related Content

PDF
Proxies are Awesome!
PPT
Advanced JavaScript
PPTX
5 Tips for Better JavaScript
PPT
Advanced Javascript
PDF
Java Script Best Practices
PDF
Advanced javascript
PPTX
Oojs 1.1
PPTX
Advanced JavaScript
Proxies are Awesome!
Advanced JavaScript
5 Tips for Better JavaScript
Advanced Javascript
Java Script Best Practices
Advanced javascript
Oojs 1.1
Advanced JavaScript

What's hot (20)

PDF
JavaScript - From Birth To Closure
PPT
Beginning Object-Oriented JavaScript
PDF
JavaScript Basics and Best Practices - CC FE & UX
PDF
Object Oriented JavaScript
PDF
Powerful JavaScript Tips and Best Practices
PPT
Advanced JavaScript
PDF
Object Oriented Programming in JavaScript
ODP
Javascript
PDF
JavaScript Design Patterns
PDF
Prototype
PPT
Object Oriented JavaScript
PDF
Ten useful JavaScript tips & best practices
PDF
Core concepts-javascript
KEY
JavaScript Growing Up
PPTX
Building native Android applications with Mirah and Pindah
PPTX
Awesomeness of JavaScript…almost
PPT
JavaScript Basics
PDF
Advanced Object-Oriented JavaScript
PPTX
Javascript basics for automation testing
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
JavaScript - From Birth To Closure
Beginning Object-Oriented JavaScript
JavaScript Basics and Best Practices - CC FE & UX
Object Oriented JavaScript
Powerful JavaScript Tips and Best Practices
Advanced JavaScript
Object Oriented Programming in JavaScript
Javascript
JavaScript Design Patterns
Prototype
Object Oriented JavaScript
Ten useful JavaScript tips & best practices
Core concepts-javascript
JavaScript Growing Up
Building native Android applications with Mirah and Pindah
Awesomeness of JavaScript…almost
JavaScript Basics
Advanced Object-Oriented JavaScript
Javascript basics for automation testing
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Ad

Similar to Javascript tid-bits (20)

PDF
Say It With Javascript
PPTX
JavaScript (without DOM)
PDF
JavaScript for PHP developers
DOC
Jsphp 110312161301-phpapp02
PDF
Let's JavaScript
PDF
JavaScript Survival Guide
PPTX
Ian 20150116 java script oop
ODP
ES6 PPT FOR 2016
PDF
JS Level Up: Prototypes
PDF
The many facets of code reuse in JavaScript
PDF
JavaScript Inheritance
PDF
Javascript
PDF
Uncommon Design Patterns
PDF
Java script object model
PDF
JavaScript Core
PPTX
Advanced JavaScript
PPT
Javascript quiz. Questions to ask when recruiting developers.
PDF
The Beauty of Java Script
PDF
The Beauty Of Java Script V5a
Say It With Javascript
JavaScript (without DOM)
JavaScript for PHP developers
Jsphp 110312161301-phpapp02
Let's JavaScript
JavaScript Survival Guide
Ian 20150116 java script oop
ES6 PPT FOR 2016
JS Level Up: Prototypes
The many facets of code reuse in JavaScript
JavaScript Inheritance
Javascript
Uncommon Design Patterns
Java script object model
JavaScript Core
Advanced JavaScript
Javascript quiz. Questions to ask when recruiting developers.
The Beauty of Java Script
The Beauty Of Java Script V5a
Ad

Javascript tid-bits

  • 1. Insights into Javascript Some things you should probably know
  • 2. Play along... firebug console is your friend We’ll use console.log(...) a lot
  • 4. boolean number string undefined var b = true; var s = “hello”; var n = 45; typeof h == ‘undefined‘ // true s.length // 5
  • 5. Everything else is an Object
  • 6. All objects have properties. you can make them anytime. // Custom Objects var obj = new Object(); obj[‘name’] = ‘Kurt’; obj[true] = 45; obj[1138] = ‘trooper’; // Builtin Objects var d = new Date(); var a = new Array(1,2,3); var rx = new RegExp(/^perl$/);
  • 7. This works with any object. Including built-ins. var now = new Date(); now[5] = ‘hello’; console.log(now[5]); // ‘hello’
  • 8. Accessing objects has 2 flavors. Nearly everything in javascript is mutable! obj[‘thing’] = ‘a’ // is the same as ... obj.thing = ‘a’ console.log(obj[‘thing’]); // ‘a’ console.log(obj.thing); // ‘a’
  • 9. { Scope! } not the mouthwash
  • 10. 3 Kinds of Scope ★ Global (in a browser it’s ‘window’) ★ Local (or Function) ★ Eval (same as local)
  • 11. Scoping examples... var a = 4; // global scope function fn(a) { // local scope return (a + 2); } console.log(fn(a)); // = 6 console.log(a); // = 4 console.log(window.a); // = 4 var p = ‘a’; function prefix(s) { // p has local scope in eval var p = ‘pre_’; eval(“var ps = p + s;”); // bad, usually no need return ps; } console.log(p); // ‘a’
  • 12. Managing scope using Namespaces. function foo() { /*...*/ } // Namespace, don’t step on global ‘foo()’ var Util = {}; Util.foo = function() { // do stuff } Util.sub = {}; // nested namespaces Util.sub.bar = 1138;
  • 14. What’s (in) that object? // define an object... var n = { fn: function() { }, a: 5 }; console.log(typeof n); // ‘object’ console.log((n instanceof Object)); // true for (prop in n) { if (n.hasOwnProperty(prop)) { console.log('[' + (typeof n[prop]) + '] ' + prop); } }
  • 15. Functions() { that’s all you need, really. }
  • 16. What can’t you do with functions? // functions with arguments function add(a,b) { return a + b; } sum = add(2,2); // sum = 4 // Same as this (ref to anonymous function) var add = function(a,b) { return a + b; } sum = add(2,2); // sum = 4 // Call it now! (immediate anonymous functions)! var sum = (function(a,b){ return a+b; })(2,2); // sum = 4
  • 17. Function Idioms in Javascript This is SO common, you really need to understand it. // functions returning functions!?,... wtf?! var inc = (function() { var i = 0; return function() { return i++; } })(); // anonymous function creates closed scope console.log(inc()); // <= 0 console.log(inc()); // <= 1 This is called a closure, more later...
  • 18. More Function Idioms // Variable arguments and ‘arguments’ function show() { for (var i=0; i < arguments.length; i++) { console.log(arguments[i]); } } // prints each argument show(1,'cat',function(){}); // 1,‘cat’, function() // functions are still objects console.log('show.name = ' + show.name); console.log('show.length = ' + show.length); // Can’t reassign to name or length show.prototype.name = 'cow'; console.log('show.name = ' + show.name);
  • 19. Gaining closure on closures... ★ closures are the locally scoped variables in a function, kept around after the returned function goes out of scope ★ The returned function references the locally scoped variables, so the garbage collector retains the references to them. ★ the closure variables are only accessible to the returned function (private parts) ★ We’ll revisit this later talking about objects and inheritance.
  • 21. 3 Object Creation Patterns All of these create new object instances // Using the builtin Object var obj = new Object(); // Object.create not always supported var obj = Object.create(obj); // via a Constructor function Obj() {}; var obj = new Obj(); // Literal objects var obj = { /* .... */ }
  • 22. Constructors and new. Javascript is a classless language, but we can fake it. // Constructor function (a class) function Person(nm) { this.name = nm || ‘’; } // new instance of Person var me = new Person(‘Dave’); new Person(‘Aish’); // this == window console.log(window.name); // ‘Aish’ console.log(me.name); // ‘Dave’ console.log(me.constructor); // Person
  • 23. Objects can’t do much without methods. function Person(s) { this.name = s || ‘’; } Person.prototype.hello = function() { return ‘Hi, my name is ‘ + this.name; } var me = new Person(‘Dave’); console.log(me.hello()); // = ‘Hi, my name is Dave’
  • 24. Wait, what was that ‘prototype’ thingy? ★ All objects have a prototype (except object literals) ★ the prototype contains an object that the container object is based on (similar to inheritance) ★ Containing object has all the methods & properties of prototype through prototype chain; and that prototype’s prototype, ad infinitum... ★ All newly created objects, by default, have the builtin Object as their prototype.
  • 25. The prototype chain ★ Functions are objects, and all functions have a prototype property (even some native types). ★ The prototype property refers to the object that will be assigned as the prototype to all instances created when this function is used as a constructor. ★ Accessing a member/method follows the chain: ★ your object instance (this) ★ your object’s prototype object ★ your object’s prototype’s prototype ★ and so on ...
  • 26. Modifying prototype later... function Person(s) { this.name = s || ‘’; } Person.prototype.hello = function() { return ‘Hi, my name is ‘ + this.name; } var me = new Person(‘Dave’); me.hello(); // = ‘Hi, my name is Dave’ Person.prototype.hello = function() { return ‘Hola, me llamo es ‘ + this.name; } var you = new Person(‘Kurt’); you.hello(); // = ‘Hola, me llamo es Kurt’ me.hello(); // = ‘Hola, me llamo es Dave’
  • 27. // Create a global object constructor function User(name, age) { this.name = name; // public this.age = age; var id = null; // private // Private method function genId() { return (User.idSeed++)+1000; } id = genId(); // Privileged method this.getId = function() { return id; } } User.idSeed = 1; // static member // Public methods (added to prototype) User.prototype = { getName: function() { return this.name; }, setName: function(nm) { this.name = nm; } } var emp = new User("Dave", 35); // 2 new instances var emp2 = new User("Francis", 40); console.log(emp.getId()); // 1001 console.log(emp2.getId()); // 1002
  • 28. Additional Notes on Previous Code ★ private variables can only be accessed by the constructor or privileged methods (due to closure) ★ public methods should always be defined in the object’s prototype: it’s faster and saves memory ★ this always refers to the invoking object (which can be hacked using .call() or .apply(), e.g. ★ User.getName.call(window, ‘Bob’), or ★ User.getName.apply(window, [ ‘Bob’])
  • 29. Object Inheritance No one really likes children.
  • 30. Prototypal Inheritance (nearly) // Parent ‘class’ var Person = function(s) { this.name = s || 'n/a'; } // Child ‘class’ (inherits from Person) var Employee = function(s,t) { this.title = t || "code monkey"; } Employee.prototype = new Person(); var e = new Employee('Jim Relling', 'Java Master'); console.log((e instanceof Employee)); // true console.log((e instanceof Person)); // true console.log(e.name); // ‘n/a’
  • 31. Why nearly? ★ (1) When assigning a new Person object as the prototype for Employee, Employee objects don’t get their own local copy of the prototype’s properties. This means: ★ e.name isn’t set, we get the default for the prototype object’s constructor. ★ our new Employee object doesn’t properly execute any code that SHOULD have been executed in it’s parent constructor.
  • 32. Why nearly? ★ (2) Informationally, Employee’s constructor is incorrect and will report ‘Person’ instead. emp.constructor.name; // ‘Person’ emp.constructor === Person; // true ★ this is for the most part just informational; however, some libraries and browsers might use the constructor property in edge cases. ★ plus, semantically and logically, the constructor for an object should be associated with the Function that constructed it, e.g. emp.constructor.name == ‘Employee’; // yes!
  • 33. Prototypal Inheritance (issues corrected) // Parent ‘class’ var Person = function(s) { this.name = s || 'n/a'; } // Child ‘class’ (inherits from Person) var Employee = function(s,t) { Person.call(this, s); // (1) this.title = t || "code monkey"; } Employee.prototype = new Person(); Employee.prototype.constructor = Employee; // (2) var e = new Employee('Jim Relling', 'Java Master'); console.log((e instanceof Employee)); // true console.log((e instanceof Person)); // true
  • 34. Prototypal Inheritance wrap it all up var inherit = (function () { var F = function () {}; return function (C, P) { F.prototype = P.prototype; C.prototype = new F(); C.base = P.prototype; C.prototype.constructor = C; } }()); function Parent() { /*...*/ } function Child() { Child.base.constructor.apply(this, arguments); // ... } inherit(Child, Parent);

Editor's Notes