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

1. JavaScript Objects > Instantiating Constructors Using the new Operator

Instantiating Constructors Using the new Operator

A constructor function is basically a cookie cutter template used to create pre-configured objects. Take String() for example. This function, when used with the new operator [new String('foo')] creates a string instance based on the String() “template.” Let’s look at an example.

Live Code

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

var myString = new String('foo');

console.log(myString); // logs foo {0 = "f", 1 = "o", 2 = "o"}

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

Above, we created a new string object that is an instance of the String() constructor function. Just like that, we have a string value expressed in JavaScript.

Note

I’m not suggesting that you use constructor functions instead of their literal/primitive equivalents—like var string="foo";. I am, however, suggesting that you understand what is going on behind literal/primitive values.


  

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