I am trying to learn some new concepts about javascript.Here is a simple code I wrote. Inside a function THIS keyword refers to global object which is window unless it's bind with the context of another object. Inside myobj object there are two methods which shares a same name with another two globally accessible function called afunc and anotherfunc respectively. I want to access those global function within myobj context and of course without using binding global object to a immediately invoked function which I used to call them. But it is throwing an error. My question is if everything in javascript is an object and window object holds them ,then why can i access those function using this.afucn or window.afunc?
(function(){
var afunc=function (){
document.write('this is world'+'</br>');
}
var anotherfunc=function (){
document.write('this is another world');
}
var myobj={
afunc:function(){
document.write('afunc');
},
anotherfunc:function(){
document.write('anotherfunc');
},
context:function(){
(function(){
this.afunc();
this.anotherfunc();
})();
}
};
myobj.context();
})();
It is true that in your case, this will refer to the global object and this.afunc(), etc will access the global variable afunc.
However, unless there is more code to show, you don't have a global variable afunc. The variables you defined with
(function(){
var afunc=function (){
document.write('this is world'+'</br>');
}
var anotherfunc=function (){
document.write('this is another world');
}
//...
})();
are local to the enclosing function (the (function(){ ... })(); part).
If you want to make them global, you can just move them outside the function:
var afunc = function() {
document.write('this is world' + '</br>');
};
var anotherfunc = function() {
document.write('this is another world');
};
(function() {
var myobj = {
afunc: function() {
document.write('afunc');
},
anotherfunc: function() {
document.write('anotherfunc');
},
context: function() {
(function() {
this.afunc();
this.anotherfunc();
})();
}
};
myobj.context();
})();
However, note that in strict mode, this would be undefined, not referring to the global object. This was done because usually if someone uses this inside a function, they don't expect it to refer to the global object. By just looking at the code, it's not always clear whether you want to access the global object (via this) or some other object (and as you noticed, there was some confusion about your intend).
That's why, if you want to access the global object, you should do so explicitly and refer to it via window.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With