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 > Replacing the prototype Property with a New Ob...

Replacing the prototype Property with a New Object Removes the Default Constructor Property

It’s possible to replace the default value of a prototype property with a new value. Doing so, however, will eliminate the default constructor property found in the “pre-made” prototype object—unless you manually specify one.

In the code below, we create a Foo constructor function, replace the prototype property with a new empty object, and verify that the constructor property is broken (it now references the less useful Object() constructor).

Live Code

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

var Foo = function Foo(){};

Foo.prototype = {}; // replace prototype property with an empty object

var FooInstance = new Foo();

console.log(FooInstance.constructor === Foo); /* logs false, 
                                              we broke the reference */
console.log(FooInstance.constructor); // logs Object(), not Foo()

// compare to code where we do not replace the prototype value

var Bar = function Bar(){};

var BarInstance = new Bar();

console.log(BarInstance.constructor === Bar); // logs true
console.log(BarInstance.constructor); // logs Bar()

</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 10-Day Trial


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