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 Does Not Update Former Instances

You might think that you can replace the prototype property entirely at any time and that all instances will be updated, but this is not correct. When you create an instance, that instance will be tied to the prototype that was “minted” at the time of instantiation. Providing a new object as the prototype property does not update the connection between instances already created and the new prototype.

But remember, as I stated above, you can update or add to the originally created prototype object and those values remain connected to the first instance(s).

Live Code

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

var Foo = function Foo(){};

Foo.prototype.x = 1;

var FooInstance = new Foo();

console.log(FooInstance.x); // logs 1, as you think it would

// now let's replace/override the prototype object with a new Object() object
Foo.prototype = {x:2};

console.log(FooInstance.x); /* logs 1, WHAT? Shouldn't it log 2, we just updated prototype */
/* FooInstance still references the same state of the prototype object that
was there when it was instantiated. */

// create a new instance of Foo()
var NewFooInstance = new Foo();

// the new instance is now tied to the new prototype object value (i.e., {x:2};)
console.log(NewFooInstance.x); // logs 2

</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