Reputation: 189
Given the following Javascript example:
var obj = function() {
var _c = function() {
console.log("c")
}
return {
a: function() {
b();
},
b: function() {
console.log("b");
},
c: function() {
_c();
}
}
}();
calling obj.a()
gives an error that b is not defined. This error can be solved by changing b()
to this.b()
. Can anyone help explain why this is necessary while c
can access _c
?
Upvotes: 1
Views: 105
Reputation: 1132
Need to use this.b
because you are returning an object and 'b' in this context is the property of that object. you need to explicitly stated that using this
While _c is a local function defined inside the closure, you can access access it directly in the return object and does not refer to the return object.
Upvotes: 0
Reputation: 1092
You should not call b() directly.
var obj = function() {
var _c = function() {
console.log("c")
}
return {
b: function() {
console.log("b");
},
a: function() {
this.b();
},
c: function() {
_c();
}
}
}();
obj.a();
Explanation added :
You are calling b() inside a function where b() is defined on the object. So to call the function b() inside any other function, you should call b with reference to the object like
this.b();
Upvotes: -1
Reputation: 198436
_c
is a local variable that is in scope when _c()
is executed. b
is not; it is only found on the object itself, so it can be found by this.b
.
This confusion is indicative of transplanting object-oriented concepts from other languages to JavaScript. There are no private and public members in JS, and you can't call methods on the same object by leaving the object prefix. There's just local variables (v
when var v
or let v
), global variables (v
when no var v
or let v
) and object properties (obj.prop
). A method is object property that contains a function; no more, no less.
Upvotes: 2