Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

8. Function Prototype Property > User-Defined Constructors Can Leverage the Sam...

User-Defined Constructors Can Leverage the Same Prototype Inheritance as Native Constructors

Hopefully at this point in the chapter it is sinking in how JavaScript itself leverages the prototype property for inheritance (e.g., Array.prototype). This same pattern can be leveraged when creating non-native, user-defined constructor functions. Below, we take the classic Person object and mimic the pattern that JavaScript uses for inheritance.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var Person = function() {};

// all Person instances inherit a legs, arms, and countLimbs properties
Person.prototype.legs = 2;
Person.prototype.arms = 2;
Person.prototype.countLimbs = function() {return this.legs + this.arms;};

var chuck = new Person();

console.log(chuck.countLimbs()); // logs 4

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint