@@ -20,7 +20,8 @@ of steps:
20
20
- Otherwise, the function is being invoked as a standalone function not
21
21
attached to any object, and ` this ` will refer to the global object.
22
22
23
- <javascript caption =" A function invoked using Function.call " >
23
+ ``` js
24
+ // A function invoked using Function.call
24
25
var myObject = {
25
26
sayHello : function () {
26
27
console .log (' Hi! My name is ' + this .myName );
@@ -35,9 +36,10 @@ var secondObject = {
35
36
36
37
myObject .sayHello (); // logs 'Hi! My name is Rebecca'
37
38
myObject .sayHello .call (secondObject); // logs 'Hi! My name is Colin'
38
- </ javascript >
39
+ ```
39
40
40
- <javascript caption =" A function created using Function.bind " >
41
+ ``` js
42
+ // A function created using Function.bind
41
43
var myName = ' the global object' ,
42
44
43
45
sayHello = function () {
@@ -52,9 +54,10 @@ var myObjectHello = sayHello.bind(myObject);
52
54
53
55
sayHello (); // logs 'Hi! My name is the global object'
54
56
myObjectHello (); // logs 'Hi! My name is Rebecca'
55
- </ javascript >
57
+ ```
56
58
57
- <javascript caption =" A function being attached to an object at runtime " >
59
+ ``` js
60
+ // A function being attached to an object at runtime
58
61
var myName = ' the global object' ,
59
62
60
63
sayHello = function () {
@@ -75,17 +78,17 @@ myObjectHello(); // logs 'Hi! My name is Rebecca'
75
78
sayHello (); // logs 'Hi! My name is the global object'
76
79
myObject .sayHello (); // logs 'Hi! My name is Rebecca'
77
80
secondObject .sayHello (); // logs 'Hi! My name is Colin'
78
- </ javascript >
81
+ ```
79
82
80
- <div class =" note " markdown = " 1 " >
83
+ <div class =" note " >
81
84
When invoking a function deep within a long namespace, it is often tempting to
82
85
reduce the amount of code you need to type by storing a reference to the actual
83
86
function as a single, shorter variable. It is important not to do this with
84
87
instance methods as this will cause the value of ` this ` within the function to
85
88
change, leading to incorrect code operation. For instance:
86
89
</div >
87
90
88
- < javascript >
91
+ ``` js
89
92
var myNamespace = {
90
93
myObject : {
91
94
sayHello : function () {
@@ -99,14 +102,14 @@ var myNamespace = {
99
102
var hello = myNamespace .myObject .sayHello ;
100
103
101
104
hello (); // logs 'Hi! My name is undefined'
102
- </ javascript >
105
+ ```
103
106
104
107
105
- <div class =" note " markdown = " 1 " >
108
+ <div class =" note " >
106
109
You can, however, safely reduce everything up to the object on which the method is invoked:
107
110
</div >
108
111
109
- < javascript >
112
+ ```
110
113
var myNamespace = {
111
114
myObject : {
112
115
sayHello : function() {
@@ -120,4 +123,4 @@ var myNamespace = {
120
123
var obj = myNamespace.myObject;
121
124
122
125
obj.sayHello(); // logs 'Hi! My name is Rebecca'
123
- </ javascript >
126
+ ```
0 commit comments