[英]How do you perform operations on an existing closure?
Creating the closure is easy but using it is confusing for me. 创建闭包很容易,但是使用它对我来说很混乱。 Here is my closure.
这是我的封信。 Once I have it I need to be able to call operations on it like doWork, calculateThis, doAnimation, etc. but there doesn't seem to be a way to access functions inside the closure.
一旦有了它,我就需要能够对其进行调用,例如doWork,calculateThis,doAnimation等,但是似乎没有办法访问闭包内部的函数。
function worker(input) {
return function () {
doWork = function () {
alert("doing work");
};
}
}
function caller() {
var myWorker = worker();
myWorker.doWork(); // this fails
}
*The question you're asking appears subjective and is likely to be closed. *您要问的问题似乎是主观的,很可能已被关闭。 - Thanks again stackoverflow
-再次感谢stackoverflow
I believe this is what you are asking for: 我相信这是您要的:
function worker(input) {
return {
doWork: function () {
alert("doing work");
},
doAnimation: function() {
alert("animating");
}
}
}
You can now call it using your code: 您现在可以使用您的代码来调用它:
var myWorker = worker();
myWorker.doWork();
myWorker.doAnimation();
Note that your code is not really using closures, but this one does: 请注意,您的代码并未真正使用闭包,但此代码可以:
function worker(input) {
return {
doWork: function () {
alert("doing work: " + input);
},
doAnimation: function() {
alert("animating: " + input);
}
}
}
var workerA = worker('A');
var workerB = worker('B');
workerA.doWork();
workerB.doAnimation();
Can you see the difference? 你能看到区别么?
You are trying to execute a method work() but in your example you return a function, not an object with a property "work". 您正在尝试执行work()方法,但是在您的示例中,您返回的是函数,而不是具有“ work”属性的对象。
Here's what you're probably after: 这可能是您想要的:
function worker(input) {
return {
work: function () {
alert("doing work");
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.