This section provides a quick description of the built-in default method called 'hasOwnProperty()'. A tutorial example is provided to use 'hasOwnProperty()' method to test which property is local to this object and which is inherited.
From the previous section, we learned that "Object.prototype" has a method called "hasOwnProperty()",
which will be inherited by all objects in JavaScript.
From any object, you can use the "hasOwnProperty(prop)" method to test whether the specified property
is local to this object.
With this nice tool, I want to revisit my "Book" object example to check different properties at different
inheritance level with this tutorial example:
<html>
<!-- Inheritance_hasOwnProperty_Method.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Using "hasOwnProperty" Method</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Setting up my constructor, prototype and object
function Book(title, author) {
this.title = title;
this.author = author;
}
Book.prototype.price = 9.99;
Object.prototype.copyright = "herongyang.com";
var myBook = new Book("JavaScript Tutorials", "Herong Yang");
// Dumping built-in properties at the base prototype level
document.writeln("\nObject.prototype's built-in properties:");
dumpProperty(Object.prototype, "constructor");
dumpProperty(Object.prototype, "hasOwnProperty");
dumpProperty(Object.prototype, "isPrototypeOf");
dumpProperty(Object.prototype, "toString");
dumpProperty(Object.prototype, "valueOf");
// Dumping built-in properties at the my prototype level
document.writeln("\nBook.prototype's built-in properties:");
dumpProperty(Book.prototype, "constructor");
dumpProperty(Book.prototype, "hasOwnProperty");
dumpProperty(Book.prototype, "isPrototypeOf");
dumpProperty(Book.prototype, "toString");
dumpProperty(Book.prototype, "valueOf");
// Dumping built-in properties at the object level
document.writeln("\nmyBook's built-in properties:");
dumpProperty(myBook, "constructor");
dumpProperty(myBook, "hasOwnProperty");
dumpProperty(myBook, "isPrototypeOf");
dumpProperty(myBook, "toString");
dumpProperty(myBook, "valueOf");
function dumpProperty(object, property) {
var inheritance;
if (object.hasOwnProperty(property))
inheritance = "Local";
else
inheritance = "Inherited";
document.writeln(" "+property+": "+inheritance+": "
+object[property]);
}
</script>
</pre>
</body>
</html>
Built-in default properties and methods are indeed inherited by "Book.prototype" and "myBook".
But there is one exception. "Book.prototype" has a local copy of "constructor" which points to "Book()".
This tells us that JavaScript created a local property "constructor" in "Book.prototype",
instead of inheriting it from "Object.prototype".