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

The 'New' Keyword in JavaScript

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

The 'New' Keyword in JavaScript

Avatar for Chris Bateman

Chris Bateman

April 16, 2014

More Decks by Chris Bateman

Other Decks in Programming

Transcript

  1. var simpleObject = { a: 'a' }; { a: 'a'

    } simpleObject.toString(); // um, where does this function come from?
  2. var simpleObject = { a: 'a' }; { a: 'a',

    __proto__: { ... toString: function, hasOwnProperty: function, ... } }
  3. var Demo = function() { this.prop = 'text'; }; Demo.prototype.action

    = function() { alert(this.prop); }; var myDemo = Demo(); myDemo; // undefined myDemo.action() // ERROR window.prop; // 'text'
  4. var Demo = function() { this.prop = 'text'; }; Demo.prototype.action

    = function() { alert(this.prop); }; var myDemo = Demo(); myDemo; // { prop:'a', action:function } window.prop; // undefined myDemo.action(); // alerts "text"
  5. var Demo = function() { this.prop = 'text'; }; Demo.prototype.action

    = function() { alert(this.prop); }; var myDemo = new Demo();
  6. var Demo = function() { this.prop = 'text'; }; Demo.prototype.action

    = function() { alert(this.prop); }; var myDemo = new Demo();
  7. var Demo = function() { this.prop = 'text'; }; Demo.prototype.action

    = function() { alert(this.prop); }; var myDemo = new Demo(); var Demo = { init: function() { this.prop = 'text'; }, action: function() { alert(this.prop); } }; var myDemo = Object.create(Demo); myDemo.init();