Object-Oriented JavaScript - Third Edition by Antani Ved & Stefanov Stoyan

Object-Oriented JavaScript - Third Edition by Antani Ved & Stefanov Stoyan

Author:Antani, Ved & Stefanov, Stoyan [Antani, Ved]
Language: eng
Format: azw3, epub
Publisher: Packt Publishing
Published: 2017-01-12T05:00:00+00:00


Using object() method

Based on the idea that objects inherit from objects, Douglas Crockford advocates the use of an object() function that accepts an object and returns a new one that has the parent as a prototype:

function object(o) { function F() {} F.prototype = o; return new F(); }

If you need access to an uber property, you can modify the object() function as follows:

function object(o) { var n; function F() {} F.prototype = o; n = new F(); n.uber = o; return n; }

Using this function is the same as using extendCopy(), you take an object such as twoDee, create a new object from it, and then proceed to augmenting the new object:

var triangle = object(twoDee); triangle.name = 'Triangle'; triangle.getArea = function () { return this.side * this.height / 2; };

The new triangle still behaves the same way:

>triangle.toString(); "Shape, 2D shape, Triangle"

This pattern is also referred to as prototypal inheritance, because you use a parent object as the prototype of a child object. It's also adopted and built upon in ES5 and called Object.create(). Here is an example:

>var square = Object.create(triangle);



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.