Although jQuery's use is gradually reduced (it is still used in projects, and the efficiency is high. I usually don't need it). I hope to reduce the dependence on jQuery.
However, this chain operation method is really attractive (it seems that many new databases have adopted chain operations ).
The newbie is fearless, so he wrote the following code. It is mainly to avoid forgetting it later.
Copy codeThe Code is as follows:
Window. k = function (){
Return new k. fn. init (arguments );
}
K. fn = k. prototype = {
Init: function (){
This. length = 0;
// Var args = Array. prototype. slice. call (arguments, 0 );
Array. prototype. push. apply (this, arguments [0]);
Return this;
},
Show: function (){
Console. log (Array. prototype. slice. call (this, 0). join ("$ "));
Return this;
},
Hide: function (){
Console. log (this );
Return this;
}
}
K. fn. init. prototype = k. fn;
Console. log (k ("0", 1, 2, 3, 4, 5). show (). hide ());
This is just a chain operation. But under firbug, we can see that the returned jQuery object is an array/class array. I don't know how to implement this ..
K. fn. prototype = new Array () is not allowed. It seems a little tiring to look at jQuery source code ..
Below are some replies for netizens
In fact, the chain operation is very simple, that is, every time the operation object itself is returned, so that all methods defined by the object can be continuously called.
The simplest example:
Copy codeThe Code is as follows:
Var o = function (){
/**
Do something
*/
Return this;
}
O. prototype = {
Action1: function (){
/**
Do something
*/
Return this;
},
Action2: function (){
/**
Do something
*/
Return this;
}
}
You can call:
New o ()//
. Action1 ()//
. Action2 (); // each operation returns an instantiated o object.
It is actually equivalent to the following:
Var a = new o (); // if this is not returned, the call cannot be continued here. Because undefined is returned.
A. action1 (); // at this time, you can only operate on a (reference of the instantiated o object.
A. action2 ();
If you have used jQuery, You should have discovered it. JQuery does not require you to use new to instantiate an object. It is more convenient to use.
So we define another object to encapsulate the above mentioned o object:
Var k = function (){
Return new o ();
}
In this way, we can call:
K (). action1 (). action2 ();
I recommend a method called "function-based" to construct JS.
Copy codeThe Code is as follows:
// Bold to emphasize
// This method is fully functional on page 52nd of the essence of javascript language.
Var constructor = function (spec, my ){
Var that, other private instance variables;
My = my | {};
Add shared variables and functions to my
That = a new object
Privileged method added to that
Return that;
}