将参数传递到JavaScript中的关闭功能
-
13-10-2019 - |
题
MyLibrary.MyModule =
(
function initialise() {
this.id = id;
this.c = document.getElementById(id);
this.ctx = this.c.getContext('2d');
this.properties = {
setup: {
backgroundColour: options.setup.backgroundColour || 'black'
},
scale: {
show: options.scale.show || true,
colour: options.scale.color || 'white'
},
}
console.log(properties.setup.baseFontSize);
}
)(id, options);
我正在使用此代码使用
new MyLibrary.MyModule('c',options);
但是“ ID”和选项似乎没有定义。
有人可以帮忙吗?
解决方案
您的 MyLibrary.MyModule
本身是 undefined
. 。这是因为您正在调用一个匿名函数,没有返回值分配给它。
我认为您的意思是这样做:
MyLibrary.MyModule = function initialise(id, options) {
this.id = id;
this.c = document.getElementById(id);
this.ctx = this.c.getContext('2d');
this.properties = {
setup: {
backgroundColour: options.setup.backgroundColour || 'black'
},
scale: {
show: options.scale.show || true,
colour: options.scale.color || 'white'
},
}
console.log(properties.setup.baseFontSize);
};
现在您可以做:
var inst = new MyLibrary.MyModule('c',options);
...和 'c'
和 options
将收到作为构造函数的论点。
如果您的目的 立即调用函数表达式 是要关闭构造函数可以引用的一些默认值,然后IIFE需要 返回 引用该价值的函数。
其他提示
正如书写的那样,我认为这不会像您想要的那样做任何事情。您将“ mylibrary.mymodule”初始化为基本上没有。该“初始化”函数没有返回值,而您将其称为确实有一个。
我无法说出您要做什么,但是:
MyLibrary.MyModule = (function whatever() { /* ... */ })(id, options);
意思是,“调用功能 任何 使用参数列表,该参数列表由变量“ ID”和“变量”选项的值组成,然后在“ mylibrary”所引用的对象上设置属性“ myModule”,以从该函数调用返回的任何值。”
据我所知,当烟雾清除时,“ mylibrary.mymodule”将不会是一个功能。也许如果你解释你什么 想 它的意思是,然后有人可以帮助修复它。
您想要这样的东西:
MyLibrary.MyModule = function(id, options) {
this.id = id;
this.c = document.getElementById(id);
this.ctx = this.c.getContext('2d');
this.properties = {
setup: {
backgroundColour: options.setup.backgroundColour || 'black'
},
scale: {
show: options.scale.show || true,
colour: options.scale.color || 'white'
},
}
};
不隶属于 StackOverflow