TAILIEUCHUNG - Test Driven JavaScript Development- P8

Test Driven JavaScript Development- P8 | Creating Objects with Constructors 133 function return Listing shows a simple test to verify that objects do indeed inherit the methods. Listing Testing test should inherit properties from function var circle new Circle 6 assertEquals 12 Repeating quickly becomes cumbersome and expensive in terms of bytes to go over the wire when adding more than a few properties to the prototype. We can improve this pattern in a number of ways. Listing shows the shortest way simply provide an object literal as the new prototype. Listing Assigning diameter function return 2 circumference function return area function return Unfortunately this breaks some of our previous tests. In particular the assertion in Listing no longer holds. Listing Failing assertion on constructor equality assertEquals Circle Please purchase PDF Split-Merge on to remove this watermark. From the Library of 134 Objects and Prototypal Inheritance When we assign a new object to JavaScript no longer creates a constructor property for us. This means that the Get for constructor will go up the prototype chain until a value is found. In the case of our constructor the result is whose constructor property is Object as seen in Listing . Listing Broken constructor property test constructor is Object when prototype is overridden function function Circle assertEquals Object new Circle .constructor Listing solves the problem by assigning the constructor property manually Listing Fixing the missing constructor property constructor Circle . To avoid the problem entirely we could also extend the given prototype property in a closure