How to extend a member variable when extending a jQuery object
- 2020-03-30 02:45:02
- OfStack
Let's start with a piece of code:
This code to jQuery object to extend a member of myOwnMember, two functions getMyOwnMember, setMyOwnMember used to return and set the value of myOwnMember. But we saw that setMyOwnMember did not work, we again getMyOwnMember, return the original value. Why is that? The reason is that $("body") creates a new object each time, so the myOwnMember in $("body") is the initial value. If we change the code to:
This is what we want, because $("body") is only created once, followed by references to the body variable. However, this method still has problems in practice, because I can't always refer to the body variable on a global scale, and many times I still get dom nodes through $("body"), so how can we save the value of a jQuery object extension variable? The solution is that instead of storing variables on jQuery objects, we store them on dom nodes, and 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 as follows:
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 to jQuery object to extend a member of myOwnMember, two functions getMyOwnMember, setMyOwnMember used to return and set the value of myOwnMember. But we saw that setMyOwnMember did not work, we again getMyOwnMember, return the original value. Why is that? The reason is that $("body") creates a new object each time, so the myOwnMember in $("body") is the initial value. 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 what we want, because $("body") is only created once, followed by references to the body variable. However, this method still has problems in practice, because I can't always refer to the body variable on a global scale, and many times I still get dom nodes through $("body"), so how can we save the value of a jQuery object extension variable? The solution is that instead of storing variables on jQuery objects, we store them on dom nodes, and 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 as follows:
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