jQuery in Action

332
APPENDIX
JavaScript that you need to know but might not!
<html>
<head>
<title>Function Context Example</title>
<script>
var o1 = {handle:'o1'};
var o2 = {handle:'o2'};
var o3 = {handle:'o3'};
window.handle = 'window';
function whoAmI() {
return this.handle;
}
o1.identifyMe = whoAmI;
alert(whoAmI());
alert(o1.identifyMe());
alert(whoAmI.call(o2));
alert(whoAmI.apply(o3));
</script>
</head>
<body>
</body>
</html>
In this example, we define three simple objects, each with a
handle
property that
makes it easy to identify the object given a reference
b
. We also add a
handle
property to the
window
instance so that it's also readily identifiable.
We then define a top-level function that returns the value of the
handle
prop-
erty for whatever object that serves as its function context
c
and assign the same
function instance to a property of object
o1
named
identifyMe
d
. We can say that
this creates a method on
o1
named
identifyMe
, although it's important to note
that the function is declared independently of the object.
Finally, we issue four alerts, each of which uses a different mechanism to
invoke the same function instance. When loaded into a browser, the sequence of
four alerts is as shown in figure A.4.
Listing A.1
Demonstrating that the value of the function context is dependent on
how the function is invoked
b
c
d
e
f
g
h


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.