80 likes | 258 Views
Prototypal Inheritance. How do we share behaviour across objects. Can We Do Inheritance Without Classes?. Everything in JavaScript uses. Name/Value Pairs. Objects With Constructors. function Foo(name) { this.name = name; } Foo. prototype = { alertName : function ( ) {
E N D
How do we sharebehaviour across objects Can We Do Inheritance Without Classes?
Everything in JavaScript uses Name/Value Pairs
Objects With Constructors • function Foo(name) { • this.name = name; • } • Foo.prototype = { • alertName: function () { • alert(this.name); • } • }; • foo = new Foo("Jack”); • foo.alertName();
.prototypevs.[[prototype]] • [[prototype]] is a part of the ECMA standard and is not a property you directly access. • .prototype is only used with constructors. • You can’t use it to switch prototypes on the fly.
What sets the prototype? • new operator • Object.create() • .prototype property of a constructor function • Literals • Regexp literal, function expression, array literal • These objects all have their respective prototype object in their proto type chain.
Setting a Prototype with Object.create() • var a = {a: 1}, • b = Object.create(a); • console.log(a.a) //outputs 1 • console.log(b.a) // outputs 1 • // because a is a prototype of b. • console.log(a.isPrototypeOf(b)); • //returns true
When referencing a property of an object, JavaScript first checks the the object then its prototype(s) untilfinally undefined is returned. Note the similarity of the Prototype Chain to the Scope Chain.