简体   繁体   English

分配给匿名 function 的变量未定义

[英]variable assigned to anonymous function is not defined

I am using anonymous function assigned to a variable to minimize use of global variables.我正在使用分配给变量的匿名 function 来尽量减少全局变量的使用。 Within this function there are nested functions: one to preload and resize images, and two other nested functions for navigation (next and previous).在这个 function 中有嵌套函数:一个用于预加载和调整图像大小,以及另外两个用于导航的嵌套函数(下一个和上一个)。 The code below generates error that the variable to which the anonymous function is assigned is not defined: Cannot read property 'preload_and_resize' of undefined If you spot the problem please let me know.下面的代码生成错误,未定义分配给匿名 function 的变量:无法读取未定义的属性“preload_and_resize”如果您发现问题,请告诉我。 Thank you very much.非常感谢你。

<html>
<head>
<script type="text/javascript">
var runThisCode=(function(){
 var myImages=new Array("img/01.jpg","img/02.jpg","img/03.jpg");
 var imageObj = new Array();
 var index=0;
 var preload_and_resize=function(){
        var i = 0;
        var imageArray = new Array();
        for(i=0; i<myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src=myImages[i];
        }

    document.pic.style.height=(document.body.clientHeight)*0.95;
};
 var next_image=function(){
    index++;
    if(index<imageObj.length){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=0;
        document.pic.src=imageObj[index].src;
    }
 };
 var prev_image=function(){
    index--;
    if(index>=0){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=myImages.length-1;
        document.pic.src=imageObj[index].src;
    }
 };
})();
</script>
</head>
<body onload="runThisCode.preload_and_resize();">
<div align="center">
<img name="pic" id="pic" src="img/01.jpg"><br />
<a href="JavaScript:runThisCode.prev_image()">Prev</a><a href="JavaScript:runThisCode.next_image()">Next</a>
</div>
</body>
</html>

Your anonymous function doesn't return anything, so when you run it, undefined gets returned. 您的匿名函数不返回任何内容,因此当您运行它时,将返回undefined。 That's why runThisCode is undefined. 这就是为什么runThisCode未定义的原因。 Regardless though, with the way you've written it, preload_and_resize will be local , so you wouldn't be able to access that anyway. 无论如何,按照你编写它的方式, preload_and_resize将是本地的 ,所以无论如何你都无法访问它。

Instead, you want this anonymous function to construct an object , and reutrn that . 相反,你要这个匿名函数来构造一个对象 reutrn。 Something like this should work, or at least get you close: 这样的事情应该有用,或者至少让你接近:

var runThisCode=(function(){
 var result = {};
 result.myImages=new Array("img/01.jpg","img/02.jpg","img/03.jpg");
 result.imageObj = new Array();
 result.index=0;
 result.preload_and_resize=function(){
        var i = 0;
        var imageArray = new Array();
        for(i=0; i< result.myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src=myImages[i];
        }

    document.pic.style.height=(document.body.clientHeight)*0.95;
};
 result.next_image=function(){
    index++;
    if(index<imageObj.length){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=0;
        document.pic.src=imageObj[index].src;
    }
 };
 result.prev_image=function(){
    index--;
    if(index>=0){
        document.pic.src=imageObj[index].src;
    }
    else{
        index=myImages.length-1;
        document.pic.src=imageObj[index].src;
    }
 };

 return result;
})();

This should explain what you are doing wrong : 这应该可以解释你做错了什么:

var foobar = (function (){
   var priv1, priv2 = 'sum' , etc;
   return {
      pub_function: function() {},
      another: function() {
          console.log('cogito ergo ' + priv2 );
      }
   };

})();

foobar.another();

In respect of previous answers, my version:关于以前的答案,我的版本:

function(self) {
    let myImages = new Array("img/01.jpg", "img/02.jpg", "img/03.jpg");
    let imageObj = new Array();
    let index = 0; // if you need to expose this call with self.index

    self.preload_and_resize = function() {
        let i = 0;
        let imageArray = new Array();
        let (i = 0; i < myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src = myImages[i];
        }
        document.pic.style.height = (document.body.clientHeight) * 0.95;
    };
  
    var next_image = function() {
        index++;
        if (index < imageObj.length) {
            document.pic.src = imageObj[index].src;
        } else {
            index = 0;
            document.pic.src = imageObj[index].src;
        }
    };
  
    var prev_image = function() {
        index--;
        if (index >= 0) {
            document.pic.src = imageObj[index].src;
        } else {
            index = myImages.length - 1;
            document.pic.src = imageObj[index].src;
        }
    };
})(window.myCurrentPage = window.myCurrentPage || {});

// now you canll myCurrentPage.preload_and_resize();

You've assigned the function to the variable next_image which is scoped to the self-invoking anonymous function. 您已将该函数分配给变量next_image ,该变量的作用域是自调用匿名函数。

The value you assign to runThisCode is the return value of that anonymous function, which (since there is no return statement) is undefined . 您为runThisCode指定的值是该匿名函数的返回值,该值是(因为没有return语句) undefined

To get the code to work you need to assign an object to runThisCode and make next_image a member of it. 要使代码runThisCode ,您需要为runThisCode分配一个对象,并使next_image成为其成员。

Add the following to the end of the anonymous function: 将以下内容添加到匿名函数的末尾:

return {
    "next_image": next_image
}

Remove the anonymous function, and make your function public. 删除匿名函数,并将您的函数公开。 You will only create one global variable: the object runThisCode . 您将只创建一个全局变量:对象runThisCode

var runThisCode = function () {
    var myImages = new Array("img/01.jpg", "img/02.jpg", "img/03.jpg");
    var imageObj = new Array();
    var index = 0;
    this.preload_and_resize = function () {
        var i = 0;
        var imageArray = new Array();
        for (i = 0; i < myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src = myImages[i];
        }

        document.pic.style.height = (document.body.clientHeight) * 0.95;
    };
    this.next_image = function () {
        index++;
        if (index < imageObj.length) {
            document.pic.src = imageObj[index].src;
        } else {
            index = 0;
            document.pic.src = imageObj[index].src;
        }
    };
    this.prev_image = function () {
        index--;
        if (index >= 0) {
            document.pic.src = imageObj[index].src;
        } else {
            index = myImages.length - 1;
            document.pic.src = imageObj[index].src;
        }
    };
};

And then, later in your code: 然后,在您的代码中:

runThisCode.preload_and_resize();

should work. 应该管用。

From the invocation you've got in body onload property, it looks like what you're trying to achieve with the IIFE ( immediately invoked function expression ) is return an object that has a the method preload_and_resize . 从你在body onload属性中获得的调用,看起来你想用IIFE( 立即调用函数表达式 )实现的是返回一个具有preload_and_resize方法的preload_and_resize

As others have pointed out, you're not returning anything from the IIFE, so really all that's happening is you're closing up everything inside it in its own namespace, but not "exporting" anything. 正如其他人所指出的那样,你没有从IIFE返回任何东西,所以真正发生的一切就是你在它自己的命名空间中关闭其中的所有东西,而不是“导出”任何东西。

If you want to "export" those functions, from your IIFE, you'd probably add a final bit to it that looked something like this: 如果你想从你的IIFE“导出”那些函数,你可能会添加一个最后一点,看起来像这样:

return { 
    'preload_and_resize': preload_and_resize, 
    'next_image': next_image,
    'prev_image': prev_image
}

which essentially creates a new JavaScript object literal, and then assigns its properties to the function values from the local scope. 它实际上创建了一个新的JavaScript对象文字,然后将其属性分配给本地范围的函数值。

Some developers would find this redundant and rather than finishing out with this sort of explicit export would probably just define the functions while declaring the object literal, something like: 一些开发人员会发现这种冗余而不是完成这种显式导出可能只是在声明对象文字时定义函数,如:

return { 
    preload_and_resize: function(){
        var i = 0;
        var imageArray = new Array();
        for(i=0; i<myImages.length; i++) {
            imageObj[i] = new Image();
            imageObj[i].src=myImages[i];
        }

        document.pic.style.height=(document.body.clientHeight)*0.95;
    },
    next_image: function() {
        index++;
        if(index<imageObj.length){
            document.pic.src=imageObj[index].src;
        }
        else {
            index=0;
            document.pic.src=imageObj[index].src;
        }
    },
    prev_image: function() {
        index--;
        if(index>=0){
            document.pic.src=imageObj[index].src;
        }
        else {
            index=myImages.length-1;
            document.pic.src=imageObj[index].src;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM