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 I wrote the following: Code . It is mainly to avoid forgetting it later.
Copy code The 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. Jquery Source Code is a little tiring ..
below are some replies for netizens
In fact, the chained 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.
simplest example: copy Code the code is as follows: var o = function () {
/**
do something
*/
return this;
}< br> O. prototype = {
Action1: function () {
/**
do something
*/
return this;
},
Action2: function () {
/**
do something
*/
return this;
}< BR >}
you can call it like this:
New O () //
. action1 () //
. action2 (); // each operation returns an instantiated O object
which is actually equivalent to the following:
var A = new O (); // if this is not returned, you cannot continue calling it here. Because undefined is returned.
A. Action1 (); // at this time, you can only operate on a (the reference of the instantiated O object.
A. Action2 ();
if you have used jquery, you should find 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 previously mentioned O object:
var K = function () {
return new O ();
}< br> so that we can call it like this:
K (). action1 (). action2 ();
I recommend a JS construction method called "function. copy Code the code is as follows: // bold to emphasize
// This method is fully functional on page 52nd 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
the privileged method added to that
return that;
}