Jquery custom class encapsulation and jquery custom Encapsulation
How to Use jquery to customize a class? (Demo reference)
/* Easy to use */
(Function ($ ){
// El-manipulated object, option Attribute Value
$. Love = function (el, option ){
Var lo = $ (el );
Var lo. vars = $. extend ({}, $. love. default, option); // merged into a new object, which is a new property list.
// Define other attributes
......
Var method = {};
// Private methods. Private methods can be called to each other.
Method = {
FunctionA: function (){...},
FunctionB: function (){...},
FunctionC: function (){...},
...
}
// Public method (privileged method) for calling outside the class
This. publicFunction = function (a, B, c ){
....
/* Call a private function */
Method. functionA ();
...
}
...
}
// You can set the default attribute.
$. Love. default = {
Option1 :...,
Option2 :...,
....
}
}) (JQuery );
/* Out-of-class call */
Var a = new $. love ("# id", {title: "name", age: 12 ,...});
A. publicFunction (a, B, c );
/* Relatively advanced points */
(Function ($ ){
// El-manipulated object, option Attribute Value
$. Love = function (el, option ){
Var lo = $ (el );
Var lo. vars = $. extend ({}, $. love. default, option); // merged into a new object, which is a new property list.
// Define other attributes
......
Var method = {};
$. Data (el, "love", lo); // store data on the element, including all lo attributes and Methods
// Private methods. Private methods can be called to each other.
Method = {
FunctionA: function (){...},
FunctionB: function (){...},
FunctionC: function (){...},
...
}
// Public method (privileged method) for calling outside the class
Lo. pfunctionA = function (){
/* Call a private function */
Method. functionA ();
},
Lo. pfunctionB = function (){...},
...
}
// You can set the default attribute.
$. Love. default = {
Option1 :...,
Option2 :...,
....
}
$. Fn. love (option ){
Var $ this = $ (this );
If ($ this. data ('love') === undefined ){
New $. love (this, option );
} Else {
Var love = $ this. data ('love'); // directly use functions in the class.
Love. pfunctionA ();
}
}
}) (JQuery );
$ => "$" Is the reference of the jQuery object, which is equal to "jQuery"
(Function () {}) ==> mimic block-level scope
$. Xxx ==> add methods for jQuery objects (my understanding)
$. Fn. xxx = add methods for elements (my understanding)