[英]How to create a Set of user-defined objects in Javascript with a user-defined equality function?
[英]how to call user-defined function of a window object in javascript
我試圖從外部調用在窗口對象中定義的函數,但是會引發錯誤。
window.vcm = (function() {
"use strict";
function red(){
alert('red');
}
});
vcm.red();//Error at this line...
我是javascript的OOPS新手。 有人可以告訴我如何在這里調用此函數。
vcm
的值沒有red
屬性。
也許您的意思是相反的,其中vcm
是一個具有red
屬性的對象,可以調用該函數:
window.vcm = {
red: function(){
"use strict";
alert('red');
}
};
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"
有兩種方法。
方法1: window.vcm = { red: function (){ "use strict"; alert('red'); } }; vcm.red();
window.vcm = { red: function (){ "use strict"; alert('red'); } }; vcm.red();
方法2:
window.vcm = (function() {
"use strict";
this.red = function(){
alert('red');
}
});
var x = new vcm();
x.red();
red
僅存在於分配給window.vcm
的函數中,並且僅在執行該函數時存在。 此外,函數沒有屬性red
。
考慮以下簡單示例:
function foo() {
function bar() {}
}
bar(); // will throw an error
調用bar
將引發錯誤,因為未在調用它的作用域中定義bar
。
似乎您想將一個對象分配給具有red
屬性的window.vcm
:
window.vcm = {
red: function (){
"use strict";
alert('red');
}
};
在這里,我使用對象文字來創建具有屬性red
的對象。
更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.