Upgrade to Pro — share decks privately, control downloads, hide ads and more …

javascript advanced

javascript advanced

Ran Tavory

May 01, 2012
Tweet

More Decks by Ran Tavory

Other Decks in Programming

Transcript

  1. A few interesting fact • JavaScript is the VM of

    the world • It's the only language PPL think they don't have to learn it. ◦ When was the last time you learned JS? And not from other ppl code?! • JavaScript != Java ◦ Unlearning things is hard • Writing Java is easy. Writing JS is HARD!
  2. Unique constructs in JS • Anonymous functions • All functions

    are objects • closures • lambda calculus • prototypal inheritance • Dynamic objects • loose typing • regular expressions • eval statement • === operator • Variable scope: only functions define scope. • Everything is an object
  3. Closures var plusX = function (x){ var a = x;

    return function f(v) { return a + v; }; }; var plus5 = plusX(5); var plus2 = plusX(2); plus5(10) -> 15 plus2(10) -> 12 • A function object contains: ◦ A function (name, parameters, body) ◦ A reference to the environment in which it was created (context) • This is a VERY good things ◦ Robust code (no global variables, no global functions) ◦ High performance
  4. OOP - requirements • Encapsulation ◦ an object supports methods

    and holds its own data • Inheritance ◦ The ability for two classes to respond to the same (collection of) methods • Polymorphism ◦ The ability to define the behavior of one object in terms of another by sub-classing
  5. OOP - implementation • There is more than one way

    to implement OOP in JS • Different JS frameworks use different techniques. Use the method supported by your framework
  6. prototypal OOP function A() { // Define super class this.x

    = 1; } A.prototype.doIt = function() { // Define Method this.x += 1; } B.prototype = new A(); // Define sub-class B.prototype.constructor = B; function B() { A.call(this); // Explicitly call super-class constructor (if desired) this.y = 2; } B.prototype.doIt = function() { // Define Method A.prototype.doIt.call(this); // Call super-class method (if desired) this.y += 1; } b = new B(); // Instantiate a new B instance. *allows statics, but no private members
  7. Object based OOP in JS function C1() { // Class

    C1 console.log('Constructing C1'); function p(x) {console.log('C1.p')} // Public methods: this.f = function() {console.log('c1.f')}; this.g = function() {console.log('c1.g')}; }; function C2() { // Class C2 this.inheritFrom = C1; // Extends C1 this.inheritFrom(); console.log('Constructing C2'); // Public methods: this.f = function() {console.log('C2.f')}; }; var c2 = new C2(); c2.f(); c2.g(); * No statics, yes privates
  8. Object based OOP in JS (2) Singletons: var singleton =

    function() { var privateVar; function privateFunction(x) {...} // Public methods: return { firstMethod: function(a, b) {...}, secondMethod: function(c) {...} }; }();
  9. Ext style OOP Person = Ext.extend(Object, { constructor: function(first, last){

    this.firstName = first; this.lastName = last; } getName: function(){ return this.firstName + ' ' + this.lastName; } }); Developer = Ext.extend(Person, { getName: function(){ if(this.isCoding){ return 'Go Away!'; }else{ // Access the superclass getName method return Developer.superclass.getName.call(this); } } }); var p = new Person('John', 'Smith');
  10. Profiling JavaScript • Use FireBug profile tool • Use yslow

    • Calling a function IS unfortunately a considerable overhead
  11. Optimization tips • For iterations use arrays whenever possible, not

    object • When iterating over arrays don't call a.length at each iteration • Wrap everything in anonymous functions (function() { /* all code in your file goes here */ })(); •
  12. The bad parts • Global variables • + operator overloading

    • Automatic semicolon insertion function f(){ return // wrong. Will return undefined! { ok: false }; } • typeof ◦ typeof Object == "function" ◦ typeof Object() == "object" ◦ typeof [] == "object" - not helpful ◦ typeof null == "object" - wrong! • with statement • eval statement - only correct usage is json
  13. The bad parts (2) • Has both null and undefined,

    which are not equal. var v = o[name];if (value == null) { // Wrong! should be === undefined alert(name + ' not found');} • for..in statement mixes functions as well as members • Allows block-less statements (like in C) if (foo) bar(); • Allows expression statements: foo; is a valid expression • There's only one Number type, Floating point, but it's IEEE flawed: 0.1 + 0.2 != 0.3 • phony array (bad for performance)
  14. The bad parts (3) • Operator == does automatic coersion

    '' == 0 // false 0 == '' // true 0 == '0' //true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true ' \t\r\n ' == 0 //true • Conclusion: use === and !== ◦ Don't rely on auto-coersion; It's hard to get it right!
  15. References • JavaScript: The Good Parts (video) • Object Oriented

    Javascript best practices ? (stackoverflow) • Object Oriented Programming in JavaScript • Comparison of JavaScript Inheritance Mechanisms; Proposal • On JavaScript Inheritance Performance and Libraries Troubles • On JavaScript Inheritance Performance - One Step Back