课程: JavaScript Practice: Object-Oriented Programming
Solution: Create a function with Object.create() - JavaScript教程
课程: JavaScript Practice: Object-Oriented Programming
Solution: Create a function with Object.create()
- [Instructor] Let's first create the book object. We'll use JavaScript functions to do this. The book function takes four parameters. Title, author, quantity, and edition. We'll use this.property name to set the properties on the instance of the book object. (keyboard keys clicking) Now, we can define the set addition function using object.define property. This function allows us to either define a new property on an object, or modify an existing property. (keyboard keys clicking) Now, we can create the cell method on the book prototype. We can set this method on the prototype with book.prototype.cell. If the quantity is greater than 0, we will reduce the quantity by 1. Now we're ready to create the comic book object. We'll also use a JavaScript function to define this object. Comic book will take four parameters, title, author, quantity, and graphic artist. (keyboard keys clicking) It will not have an edition. Since there is an inherited relationship between book and comic book, as all comic books are books, but not all books are comic books, we must use the call method to pass three inherited properties, title, author, and quantity up to the book constructor. Lastly, we need to set the prototype of the comic book object to the book object. We will use the object.create function to do this. We'll pass book.prototype as the first argument to object.create to create the inherited relationship. Then, we'll establish the constructor for comic book as the comic book object. (keyboard keys clicking) When we run our code, we can see all of the test cases pass.