Home > Article > Web Front-end > Detailed explanation of JS facade pattern use cases
This time I will bring you a detailed explanation of the use cases of JS facade mode. What are the precautions when using JS facade mode? Here are practical cases, let’s take a look.
The facade pattern is a popular design pattern that creates a new interface for an existing object. A facade is a brand new object that has an existing object working behind it. Facades are sometimes called wrappers, they use different interfaces to wrap existing objects. If inheritance is not sufficient for your use case, then it is logical that the next step should be to create a facade.
jQuery and YUI’s DOM interface both use facades. As mentioned above, you cannot inherit from a DOM object, so the only option to safely add functionality to it is to create a facade. The following is an example of DOM object wrapper code:
function DOMWrapper (element) { this.element = element; } DOMWrapper.prototype.addClass = function (className) { this.element.className += ' ' + className; } DOMWrapper.prototype.remove = function () { this.element.parentNode.removeChild(this.element); }// 用法var wrapper = new DOMWrapper( document .getElementById('my-div')); wrapper.addClass('selected'); wrapper.remove();
The DOMWrapper type expects a DOM element to be passed to its constructor. The element is saved for later reference and defines some methods for manipulating the element. The addClass() method is a simple way to add className to elements that have not yet implemented the HTML5 classList attribute. The remove() method encapsulates the operation of deleting an element from the DOM, shielding developers from the need to access the parent node of the element. From the maintainability of JS, facade is a very suitable method, and you can fully control these interfaces. You can allow access to any underlying object's properties or methods and vice versa, effectively filtering access to that object. You can also modify existing methods to make them simpler and easier to use (the sample code above is an example). No matter how the underlying objects change, as long as the facade is modified, the application can continue to work normally.
A facade that implements a specific interface to make one object look like another object is called an adapter. The only difference between facades and adapters is that the former creates new interfaces, while the latter implements existing interfaces.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to avoid null comparison in web developmentHow to detect original values in web developmentThe above is the detailed content of Detailed explanation of JS facade pattern use cases. For more information, please follow other related articles on the PHP Chinese website!