Reputation: 3051
I am trying to call a function from outside which is defined with in a window object, but it throws an error.
window.vcm = (function() {
"use strict";
function red(){
alert('red');
}
});
vcm.red();//Error at this line...
I am new to OOPS in javascript. Can somebody tell me how to call this function here.
Upvotes: 2
Views: 4836
Reputation: 1668
There are two approaches.
Approach 1 :
window.vcm = {
red: function (){
"use strict";
alert('red');
}
};
vcm.red();
Approach 2 :
window.vcm = (function() {
"use strict";
this.red = function(){
alert('red');
}
});
var x = new vcm();
x.red();
Upvotes: 1
Reputation: 437376
The value that is vcm
does not have a red
property.
Perhaps you mean this instead, wherein vcm
is an object that has a property red
that is function you can call:
window.vcm = {
red: function(){
"use strict";
alert('red');
}
};
It's also a possibility (albeit not somewhat you 'd see in practice) for vcm
itself to be a function and for it to have a red
property that is a function:
window.vcm = (function() {
"use strict";
var vcm = function() { alert("vcm"); }
vcm.red = function() { alert('vcm.red'); };
return vcm;
})();
vcm(); // "vcm"
vcm.red(); // "vcm.red"
Upvotes: 2
Reputation: 816442
red
only exist inside the function you assigned to window.vcm
and also only when the function is executed. Furthermore, functions don't have a property red
.
Consider this simpler example:
function foo() {
function bar() {}
}
bar(); // will throw an error
Calling bar
will throw an error because bar
is not defined in the scope where it is called.
It seems you want to assign an object to window.vcm
, which has a property red
:
window.vcm = {
red: function (){
"use strict";
alert('red');
}
};
Here I am using an object literal to create an object with the property red
.
More information:
Upvotes: 0