jQuery is an object-oriented js library, so it also has the function of a constructor. It can form a constructor through the prototype and init() function, and the constructor implemented by jQuery does not need to use new to instantiate the object
The constructor in jquery fully utilizes the dynamics of the javascript language. Since there are no strict requirements on the type and number of row parameters, one function can fulfill multiple functional requirements. Next, in the article, I will introduce the constructor in jQuery in detail, which has a certain reference effect and I hope it will be helpful to you.
【Recommended tutorial: jQuery Tutorial】
jQuery is an object-oriented js library that also contains constructors. A jQuery object is instantiated every time a jQuery method is called, but jQuery's writing method is more clever.
The ECMA standard defines an object in JS: a collection of unordered properties, whose properties can contain basic values, objects or functions. It can be simply understood that a JS object is a set of unordered values. Each attribute or method has a name. According to this name, the mapped value can be accessed. This value can be a basic value, an object or a method
Example: Constructor case in JavaScript
<script> function Student(name, age) { this.name = name; this.age = age; } Student.prototype = { constructor : Student, demo : function() { document.write(this.name+"今年"+this.age+"岁"); } } var stu1 = new Student("小明", 20); stu1.demo(); </script>
Rendering:
Let’s take a look at how to write the constructor in jQuery
var jQuery = function(selector, context) { return new jQuery.fn.init(selector, context, rootjQuery); } jQuery.fn = jQuery.prototype = { init: function (selector, context, rootjQuery) { // ... } } jQuery.fn.init.prototype = jQuery.fn;
The above code is the key code in the jQuery constructor. It can be seen that in jQuery The real constructor is the init method. When we call jQuery, it will return the result of new init() instead of new jQuery() directly. That is, there is no need for new jQuery()
jQuery.fn = jQuery.prototype = {...} jQuery.fn.init.prototype = jQuery.fn;
when instantiating an object. The description function is the prototype object of jQuery, through which the instantiation function of the object is realized. Finally, the jQuery prototype object is copied to the init() prototype object, so the init() function has all the methods of the prototype in jQuery
Summary: The above is this This is the entire content of this article. I hope this article can help everyone understand the constructor in jQuery.
The above is the detailed content of How to understand the constructor in jquery. For more information, please follow other related articles on the PHP Chinese website!