课程: JavaScript: Five Advanced Challenges and Concepts

免费学习该课程!

今天就开通帐号,24,700 门业界名师课程任您挑!

Using singletons to create unique functions

Using singletons to create unique functions

- [Instructor] The singleton pattern is a fairly simple piece of code you can add to your class, and once you know it, you'll know how to use it for any class. In the example code for this movie, I've created a very basic class at the top here called UniqueClass. It just receives a piece of data and then returns it. So down here, I've created two instances of it, instance one and instance two, and they send in different pieces of text here. So we have data for the first instance and then data is for the second instance that shouldn't be set. Then finally, I just console.log the two instances out, and right now, if I go to my console and say node script, I get data for the first instance and the second instance should not be set, meaning we currently don't have a singleton. We're able to create multiple instances of this class. Now let's add the singleton pattern. That's done inside the constructor. We'll start by…

内容