Home > Article > Web Front-end > Detailed explanation of steps to call cache to implement JS method
This time I will bring you a detailed explanation of the steps for calling the cache to implement the JS method. What are the precautions for calling the cache to implement the JS method? The following is a practical case, let's take a look.
1. What isIn short: method overloading means repeated method names and different loading parameters.
So how does js implement this? ? ?
As for downloading, once the method parameter length is available, a more common switch writing method appears:
var seven={ dosomething:function(){ switch(arguments.length){ case 0: console.log(arguments.length); //dosomething break; case 1: console.log(arguments.length); //dosomething break; case 2: //dosomething console.log(arguments.length); break; } } }
But these are bad~difficult to maintain, and not high enough~So how should we elegantly implement the processing of the same method name with different parameters?
addMethod method for seven.
var seven = { addMethod: function (fname, func) { var old = this[fname]; this[fname] = function () { if (arguments.length == func.length) { return func.apply(this,arguments); } if (typeof old == 'function') { return old.apply(this, arguments); } } } };The modified seven is as above, and then before The switch you write can be done like this:
seven.addMethod('dosomething', function (x) { console.log(arguments.length); //dosomething }); seven.addMethod('dosomething', function (x,y) { console.log(arguments.length); //dosomething }); seven.addMethod('dosomething', function (x,y,z) { console.log(arguments.length); //dosomething });If we want to add a method, we only need to call the addMethod method. Don’t you think it is simpler and clearer?
The principle of this code is actually very simple. It is to cache the old method, and then apply chain calls in sequence according to the parameter length until a method with the same length as the current parameter is found ~ and then called.
func and
old are very likely to confuse the newbies. In fact, this is not the case. The features of the JavaScript language are cleverly used here. This old is saved every time. They are all references to the last method, and they are brand new every time, while the old old maintains a reference. What is this? Closure~.
Detailed explanation of the steps to implement full-screen scrolling plug-in in ES6
The above is the detailed content of Detailed explanation of steps to call cache to implement JS method. For more information, please follow other related articles on the PHP Chinese website!