Once
- Once
A Once class creates only one instance.
- function Once() {
- return this.constructor._instance || (this.constructor._instance = this);
- }
The function Once
creates an object whose constructor has a _instance
property.
If _instance
is undefined
, Once
keeps the object just created this
and returns it.
Otherwise, Once
returns the instance created previously.
- Once.prototype = Object.create(Objective.prototype);
Initializes the prototype of the function Once
with a copy of the prototype of the function Objective
(prototypal inheritance).
The class Once inherits from the class Objective.
- Object.defineProperty(Once.prototype, 'constructor', { value: Once, enumerable: false, writable: true });
Renames the constructor.
See the article Inheritance in JavaScript on the website MDN Web Docs.
- Once.prototype.clone = function() {
- return this;
- };
Redefines the clone
method inherited from Objective class.
Test
- <?php head('javascript', '/objectivejs/Objective.js'); ?>
- <?php head('javascript', '/objectivejs/Once.js'); ?>
Adds the tags <script src="/objectivejs/Objective.js"></script>
and <script src="/objectivejs/Once.js"></script>
to the <head>
section of the HTML document.
head
is a function of iZend.
Adapt the code to your development environment.
- console.log(new Once() === new Once()); // true
Checks if the creations of 2 instances of Once return the same object.
- function Application(name) {
- let app = Once.call(this);
- if (app === this)
- this._name = name;
- return app;
- }
- Application.prototype = Object.create(Once.prototype);
- Object.defineProperty(Application.prototype, 'constructor', { value: Application, enumerable: false, writable: true });
Defines a class Application which inherits from the class Once. An instance of Application has a name.
IMPORTANT: The last instruction return app;
specifically returns the unique instance returned by the constructor of the class Once.
- let app1 = new Application('foobar');
- let app2 = new Application('barfoo');
Creates 2 instances of Application with different names.
- console.log(app1.constructor.name); // Application
- console.log(app1 === app2); // true
- console.log(app1._name); // foobar
Displays the name of the constructor of an instance of Application. Checks that only one instance of Application has been created and that its name is the one passed as a parameter to the first instantiation.
- let app3 = app1.clone();
- console.log(app1 === app3); // true
Checks that the clone of an instance of Application is the original instance.
Display the page generated by the file testOnce.phtml and check the trace in the console of the browser:
true
Application
true
foobar
true
Comments