Reputation: 443
myObject has two functions, the first one is calling the second one, is there a way to see variable a inside callMe()?
var myObj = {
callMefirst: function() {
var thisObj = this;
var a;
a = 'chocolate cookie';
thisObj.callMe();
},
callMe: function() {
alert(a);
}
}
myObj.callMefirst();
otherwise I know I can pass it as a parameter, or set var a in global scope of the object but I'm interested to understand this specific case of scope
Upvotes: 0
Views: 3159
Reputation: 39250
you can do this in multiple ways; the following uses closure.
var myObj = (function() {
var a;
return{
callMefirst: function() {
var thisObj = this;
a = 'chocolate cookie';
thisObj.callMe();
},
callMe: function() {
alert(a);
}
}
})()
myObj.callMefirst();
Using closure with object initiation:
var myObjF = function(pass) {
var a=pass;
return{
callMefirst: function() {
var thisObj = this;
thisObj.callMe();
},
callMe: function() {
alert(a);
}
}
}
var myObj=myObjF("hello");
myObj.callMefirst();
Using function as object:
var myObjF = function(pass) {
this.a=pass;
this.callMefirst = function() {
var thisObj = this;
thisObj.callMe();
};
}
myObjF.prototype.callMe = function() {
alert(a);
}
var myObj=new myObjF("hello");
myObj.callMefirst();
Upvotes: 1
Reputation: 1479
Try this code:
var myObj = {
a:"",
callMefirst: function() {
var thisObj = this;
this.a = 'chocolate cookie';
thisObj.callMe();
},
callMe: function() {
alert(this.a);
}
}
myObj.callMefirst();
Upvotes: 0
Reputation: 9211
a
is defined within the callMefirst
function and exists only here. Remember that JavaScript has functional (lexical) scope. As such, the easiest way to let callMe
have access to a
would to be as you suggest and define it within the scope of myObj
.
Upvotes: 1
Reputation: 943207
No. Since it is defined with the var
keyword, it is scoped to the function it is defined in. It is therefore only visible to that function and to other functions defined inside that function (of which you have none).
Upvotes: 2