[英]how to call user-defined function of a window object in javascript
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. 我是javascript的OOPS新手。 Can somebody tell me how to call this function here. 有人可以告诉我如何在这里调用此函数。
The value that is vcm
does not have a red
property. vcm
的值没有red
属性。
Perhaps you mean this instead, wherein vcm
is an object that has a property red
that is function you can call: 也许您的意思是相反的,其中vcm
是一个具有red
属性的对象,可以调用该函数:
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: vcm
本身也可能是一个函数, 并且具有red
属性即函数,这也是可能的(尽管实际上您不会看到):
window.vcm = (function() {
"use strict";
var vcm = function() { alert("vcm"); }
vcm.red = function() { alert('vcm.red'); };
return vcm;
})();
vcm(); // "vcm"
vcm.red(); // "vcm.red"
There are two approaches. 有两种方法。
Approach 1 : window.vcm = { red: function (){ "use strict"; alert('red'); } }; vcm.red();
方法1: window.vcm = { red: function (){ "use strict"; alert('red'); } }; vcm.red();
window.vcm = { red: function (){ "use strict"; alert('red'); } }; vcm.red();
Approach 2 : 方法2:
window.vcm = (function() {
"use strict";
this.red = function(){
alert('red');
}
});
var x = new vcm();
x.red();
red
only exist inside the function you assigned to window.vcm
and also only when the function is executed. red
仅存在于分配给window.vcm
的函数中,并且仅在执行该函数时存在。 Furthermore, functions don't have a property red
. 此外,函数没有属性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. 调用bar
将引发错误,因为未在调用它的作用域中定义bar
。
It seems you want to assign an object to window.vcm
, which has a property red
: 似乎您想将一个对象分配给具有red
属性的window.vcm
:
window.vcm = {
red: function (){
"use strict";
alert('red');
}
};
Here I am using an object literal to create an object with the property red
. 在这里,我使用对象文字来创建具有属性red
的对象。
More information: 更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.