Home  >  Article  >  Web Front-end  >  How to expand member variables when extending jQuery objects and how to implement it_jquery

How to expand member variables when extending jQuery objects and how to implement it_jquery

WBOY
WBOYOriginal
2016-05-16 16:51:061074browse

Let’s look at a piece of code first:

Copy the code The code is 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 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:
Copy the code The code is as follows:

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:
Copy the code The code is 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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn