By reading the jquery original code, we can simulate writing a simple jquery
Like the usual
JQuery ("div"). CSS ("Color", "red");
JQuery ("#span1"). CSS ("Color", "green");
1. JQuery (), because it is a chained call, so the return is an object.
JQuery = function (selector) { return new JQuery.prototype.init (selector); } Jquery.prototype = { constructor:jquery, init:function (selector) { this.elements = Document.queryselectorall (selector); }, css:function (key, value) { ... } }
At this point, this.elements is all the conditional HTML elements
2. CSS (), set the style for all the appropriate conditions of element.
Css:function (key, value) { This.elements.forEach (element = = { Element.style[key] = value; });
3. At this point, CSS is not accessible to this.elements. Because this.elements is defined in init, and Init is a constructor. So this.elements is the attribute inside the init instance.
Jquery.prototype.init.prototype=jquery.prototype;
This way the CSS () will be able to access the this.elements.
Full code
JQuery = function (selector) { return new JQuery.prototype.init (selector); } Jquery.prototype = { constructor:jquery, init:function (selector) { this.elements = Document.queryselectorall (selector); }, css:function (key, value) { This.elements.forEach (element = > { Element.style[key] = value; }); } } Jquery.prototype.init.prototype=jquery.prototype;
The last name of the alias
Jquery.fn=jquery.prototype
JQuery = function (selector) { return new JQuery.fn.init (selector); } Jquery.fn = Jquery.prototype = { constructor:jquery, init:function (selector) { this.elements = Document.queryselectorall (selector); }, css:function (key, value) { This.elements.forEach (element = > { Element.style[key] = value; }); } } Jquery.fn.init.prototype=jquery.fn;
Test it for a moment.
Write yourself a jquery