在函数中使用 eval 来替换图层名称的前缀?
Using eval in a function to replace a prefix on layer names?
我需要编写一个函数,我可以向它传递一个字符串,它会将其中的单词“prefix”替换为该字符串的内容。因此,每次我调用该函数并向其传递一个新字符串(即 alpha、beta 等)时,它将使用该键作为前缀完全重建内部的所有层和事件。我怀疑我需要使用 eval,但我不确定在这种情况下该怎么做。
layoutViews = (prefix) ->
prefix_layer1 = new Layer
width: 100
height: 100
prefix_layer1.on Events.Click ->
buttonActions()
layoutViews(alpha)
layoutViews(beta)
我正在使用 CoffeeScript,但也欢迎使用真正的 JS 提出任何想法。我意识到这个具体问题暗示我在项目中做错了其他事情,但这主要是出于我自己的好奇心,这是否可能。
所以你想要
function build(prefix) {
window[prefix + "_hi"] = function() {
alert("hi");
};
}
这样使用:
build("test");
test_hi();
Window 只是浏览器中的全局(!坏)元素,因此您可能会考虑分配给 this
而不是 window
取决于您的使用情况。
我需要编写一个函数,我可以向它传递一个字符串,它会将其中的单词“prefix”替换为该字符串的内容。因此,每次我调用该函数并向其传递一个新字符串(即 alpha、beta 等)时,它将使用该键作为前缀完全重建内部的所有层和事件。我怀疑我需要使用 eval,但我不确定在这种情况下该怎么做。
layoutViews = (prefix) ->
prefix_layer1 = new Layer
width: 100
height: 100
prefix_layer1.on Events.Click ->
buttonActions()
layoutViews(alpha)
layoutViews(beta)
我正在使用 CoffeeScript,但也欢迎使用真正的 JS 提出任何想法。我意识到这个具体问题暗示我在项目中做错了其他事情,但这主要是出于我自己的好奇心,这是否可能。
所以你想要
function build(prefix) {
window[prefix + "_hi"] = function() {
alert("hi");
};
}
这样使用:
build("test");
test_hi();
Window 只是浏览器中的全局(!坏)元素,因此您可能会考虑分配给 this
而不是 window
取决于您的使用情况。