Javascript tid-bits

  • 2,617 views
Uploaded on

An introductory presentation I'm doing at my workplace for other developers. This is geared toward programmers that are very new to javascript and covers some basics, but focuses on Functions, …

An introductory presentation I'm doing at my workplace for other developers. This is geared toward programmers that are very new to javascript and covers some basics, but focuses on Functions, Objects and prototypal inheritance ideas.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,617
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
98
Comments
0
Likes
4

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Transcript

  • 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
  • 3. Native data types...
  • 4. boolean number string undefinedvar b = true;var s = “hello”;var n = 45;typeof h == ‘undefined‘ // trues.length // 5
  • 5. Everything else is an Object
  • 6. All objects have properties. you can make them anytime.// Custom Objectsvar obj = new Object();obj[‘name’] = ‘Kurt’;obj[true] = 45;obj[1138] = ‘trooper’;// Builtin Objectsvar 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 scopefunction fn(a) { // local scope return (a + 2);}console.log(fn(a)); // = 6console.log(a); // = 4console.log(window.a); // = 4var 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 namespacesUtil.sub.bar = 1138;
  • 13. Other idioms...
  • 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));// truefor (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 argumentsfunction 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 scopeconsole.log(inc()); // <= 0console.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 argumentshow(1,cat,function(){}); // 1,‘cat’, function()// functions are still objectsconsole.log(show.name = + show.name);console.log(show.length = + show.length);// Can’t reassign to name or lengthshow.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.
  • 20. new Making(Objects)
  • 21. 3 Object Creation Patterns All of these create new object instances// Using the builtin Objectvar obj = new Object();// Object.create not always supportedvar obj = Object.create(obj);// via a Constructorfunction Obj() {};var obj = new Obj();// Literal objectsvar 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 Personvar me = new Person(‘Dave’);new Person(‘Aish’); // this == windowconsole.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 constructorfunction 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 instancesvar emp2 = new User("Francis", 40);console.log(emp.getId()); // 1001console.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)); // trueconsole.log((e instanceof Person)); // trueconsole.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)); // trueconsole.log((e instanceof Person)); // true
  • 34. Prototypal Inheritance wrap it all upvar 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);
  • 35. Questions &Attempted Answers ?