2

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.

1
  • What error do you get? Commented Sep 23, 2013 at 9:55

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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(); 

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.