Let’s look at a piece of code first:
jQuery.fn.extend(
{
myOwnMember: 3,
getMyOwnMember: function () { return this.myOwnMember; },
setMyOwnMember: function (v) { this.myOwnMember = v; return this.myOwnMember; }
}
);
$("body").myOwnMember; //3
$("body").getMyOwnMember(); //3
$("body" ).setMyOwnMember(4); //4
$("body").getMyOwnMember(); //3
This code extends a member myOwnMember to the jQuery object, two The functions getMyOwnMember and setMyOwnMember are used to return and set the value of myOwnMember respectively. But we see that setMyOwnMember does not work. When we getMyOwnMember again, the initial value is returned. Why is this? The reason is that $("body") creates a new object every time, so myOwnMember in $("body") is the initial value every time. If we change the code to:
jQuery.fn.extend (
{
myOwnMember: 3,
getMyOwnMember: function () { return this.myOwnMember; },
setMyOwnMember: function (v) { this.myOwnMember = v; return this.myOwnMember; }
}
);
var body = $("body");
body.myOwnMember; //3
body.getMyOwnMember(); //3
body.setMyOwnMember(4); //4
body.getMyOwnMember(); //4
This is the effect we want, because $("body") only It is created once, and all subsequent references are made through the body variable. However, this method still has problems in actual use, because it is impossible for me to reference the body variable in the global scope. In many cases, I still use $("body") to obtain the dom node. In this case, how can we save a What about the value of the jQuery object extension variable? The solution is that we don't save the variables on the jQuery object, but on the dom node. No matter how many jQuery objects are created on a dom node, they all point to the same dom node. So we change the code to the following:
jQuery.fn. extend(
{
getMyOwnMember: function () { return this[0].myOwnMember; },
setMyOwnMember: function (v) { this[0].myOwnMember = v; return this[0]. myOwnMember; }
}
);
$("body").getMyOwnMember(); //undefined
$("body").setMyOwnMember(4); //4
$("body").getMyOwnMember(); //4