Although I have gradually reduced my use of jQuery now (I still use it on projects, it is more efficient. I basically don’t use it in daily life), I hope to reduce my dependence on jQuery.
But this chain operation method is really attractive (it seems that many new libraries now use chain operations).
Beginners are not afraid, so I wrote the following code. The main thing is to avoid forgetting it in the future, haha.
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 you can see that the jQuery object returns an array/class array. I want to achieve this but don't know how to do it. .
You can’t let k.fn.prototype = new Array(). It's really tiring to look at the jQuery source code. .
The following are some replies to netizens
In fact, the chain operation is very simple, that is, returning the operation object itself each time, so that all methods defined by the object itself can be continuously called.
The simplest example:
var o = function() {
/**
do something
*/
return this;
}
o.prototype = {
action1: function() {
/**
do something
*/
return this;
},
action2: function() {
/**
do something
*/
return this;
}
}
You can call it like this:
new o() //
.action1() //
.action2(); / /Every step of the operation returns an instantiated o object
It is actually equivalent to this:
var a = new o();//If this is not returned, then the call cannot be continued here. Because what is returned is undefined.
a.action1(); //At this time, you can only operate on a (a reference to 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, which is more convenient when using it.
So we define another object to encapsulate the o object mentioned above:
var k = function() {
return new o();
}
So we can call it like this Here's:
k().action1().action2();
I recommend you a method called "functionalization" to construct JS.
//Bold for emphasis
//This method is from 5.4 Functionalization on page 52 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
Add privileged method to that
return that;
}