Đang chuẩn bị liên kết để tải về tài liệu:
Test Driven JavaScript Development- P8

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

Test Driven JavaScript Development- P8 | 7.2 Creating Objects with Constructors 133 Circle.prototype.area function return this.radius this.radius Math.PI Listing 7.17 shows a simple test to verify that objects do indeed inherit the methods. Listing 7.17 Testing Circle.prototype.diameter test should inherit properties from Circle.prototype function var circle new Circle 6 assertEquals 12 circle.diameter Repeating Circle.prototype 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 7.18 shows the shortest way simply provide an object literal as the new prototype. Listing 7.18 Assigning Circle.prototype Circle.prototype diameter function return this.radius 2 circumference function return this.diameter Math.PI area function return this.radius this.radius Math.PI Unfortunately this breaks some of our previous tests. In particular the assertion in Listing 7.19 no longer holds. Listing 7.19 Failing assertion on constructor equality assertEquals Circle circle.constructor Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. From the Library of WoweBook.Com 134 Objects and Prototypal Inheritance When we assign a new object to Circle.prototype 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 Object.prototype whose constructor property is Object as seen in Listing 7.20. Listing 7.20 Broken constructor property test constructor is Object when prototype is overridden function function Circle Circle.prototype assertEquals Object new Circle .constructor Listing 7.21 solves the problem by assigning the constructor property manually Listing 7.21 Fixing the missing constructor property Circle.prototype constructor Circle . To avoid the problem entirely we could also extend the given prototype property in a closure