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

JavaScript Prototype Programming

JavaScript Prototype Programming

"JavaScript Prototype Programming" is a short talk on how to properly use the prototype aspect of JavaScript to code effectively.

Rubens Mariuzzo

January 13, 2015
Tweet

More Decks by Rubens Mariuzzo

Other Decks in Programming

Transcript

  1. A style of object-oriented programming in which behavior reuse is

    performed via a process of cloning existing objects that serve as prototypes. — Wikipedia
  2. A style of object-oriented programming in which inheritance is performed

    via delegation to existing objects that serve as prototypes. — Wikipedia
  3. var Fun = function() { this.key = value; }; var

    obj = new Fun(); 2. Creating an object from function
  4. Almost all objects has a prototype link, at the time

    of their creation. That implicit prototype link is a reference to another object.
  5. - foo obj1 - foo obj2 obj1.foo resolves to obj2.foo

    because obj1 delegates to obj2 PROTOTYPE LINK
  6. Adding methods to Object.prototype has a very high risk of

    breaking something. Don’t do that. Point.
  7. A prototype property is automatically created for every function. That

    explicit prototype property is a reference to a prototype for new objects.
  8. var Foo = function () {}; Foo.prototype.bar = 123; var

    obj = new Foo(); obj - prototype Foo
  9. var Foo = function () {}; Foo.prototype.bar = 123; var

    obj = new Foo(); obj.bar; // Output: 123
  10. var A = function() {}; A.prototype.p1 = 101; var B

    = function() {}; B.prototype.p2 = 202;
  11. var A = function() {}; A.prototype.p1 = 101; var B

    = function() {}; B.prototype = Object.create(A.prototype); B.prototype.p2 = 202;
  12. var A = function() {}; A.prototype.p1 = 101; var B

    = function() {}; B.prototype = Object.create(A.prototype); B.prototype.p2 = 202; var obj = new B(); obj.p1; // Output: 101 obj.p2; // Output: 202
  13. var A = {}; A.p1 = 101; var B =

    Object.create(A); B.p2 = 202;
  14. var A = {}; A.p1 = 101; var B =

    Object.create(A); B.p2 = 202; var b1 = Object.create(B); b1.p1; // Output: 101 b1.p2; // Output: 202
  15. var obj1 = { a: 1 }; var obj2 =

    Object.create(obj1); obj2.a++; // Output: ?
  16. var obj1 = { a: 1 }; var obj2 =

    Object.create(obj1); obj2.a++; // obj1.a: 1 // obj2.a: 2
  17. ✓ Prototype Programming is a style of OOP. ✓ Objects

    has implicit prototype link, when created. ✓ Properties are resolved through prototype chain. ✓ Functions has an explicit prototype property. SUMMARY