标签: iife

立即调用函数表达式 (IIFE) 与非立即调用函数表达式

我看到很多这样的代码:

var myApp ={};
(function() {
    console.log("Hello");
    this.var1 = "mark";     //"this" is global, because it runs immediately on load.  Caller is global
    myApp.sayGoodbye = function() {
        console.log("Goodbye");
    };
})();
Run Code Online (Sandbox Code Playgroud)

这会导致匿名函数立即执行。但与仅仅将代码内联相比,这样做有什么好处呢?

var myApp ={};
console.log("Hello");
var1 = "mark";     
myApp.sayGoodbye = function() {
    console.log("Goodbye");
};
Run Code Online (Sandbox Code Playgroud)

显然这与函数的作用域有关,但由于该函数是匿名的并且由窗口调用,因此它的作用域(即this)是全局的,不是吗?

javascript design-patterns anonymous-function iife

2
推荐指数
1
解决办法
3805
查看次数

在 node.js (Windows) 中对 IIFE 的奇怪观察

nodejs 是否需要以下行为?对我来说它看起来很糟糕。如果不是我错过了什么?

var abc = function(){
console.log("hello");
}

(function(){
  console.log("welcome");
})();
Run Code Online (Sandbox Code Playgroud)

我得到以下异常

TypeError: undefined is not a function
    at Object.<anonymous> (C:\node\main.js:8:3)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
Run Code Online (Sandbox Code Playgroud)

如果我将代码更改为

var abc = function(){
console.log("hello");
}

(function(){
  console.log("welcome");
}());
Run Code Online (Sandbox Code Playgroud)

它产生

欢迎你好

我不得不相信节点解析错误地假设嵌套的 IIFE (function(){...})())首先执行,而 IIFE 的外部 () 触发它上面的函数定义的执行(如果我引入一个abc 定义和 IIFE 之间的注释行)。

javascript node.js iife

2
推荐指数
1
解决办法
1268
查看次数

将参数传递给 Go IIFE(遵循 javascript 示例)

我习惯于在 javascript 中编程,我可以执行以下操作将参数传递给立即调用的函数表达式:

(function(twoSeconds) {
    // do something with "twoSeconds" here
})(2 * 1000);
Run Code Online (Sandbox Code Playgroud)

所以我希望能够在 Go 中做类似的事情,如下所示。但是,它似乎不起作用。

func (twoSeconds) {
    // build error: "twoSeconds" undefined
}(time.Second * 2)
Run Code Online (Sandbox Code Playgroud)

所以我必须这样做:

func () {
    twoSeconds := time.Second * 2
}()
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是如何将参数传递给 Go IIFE?如果不可能,为什么不呢?

javascript go iife

2
推荐指数
1
解决办法
637
查看次数

如何使用带有 angular 6 的 save-svg-as-png

我正在尝试在我的 angular 7 项目中使用save-svg-as-png库。

但是,我无法让它发挥作用。我已经使用

npm install --save save-svg-as-png
Run Code Online (Sandbox Code Playgroud)

我可以在 node_modules 下看到库。

不幸的是,该库是一个旧式的 javascript 库,我不知道我需要做什么才能在我的打字稿组件中访问它。

自述文件引用了显然存在类型定义Typings库。但是,Typings 页面提到它在 TypeScript 2 中已被弃用,所以我没有追求这个。

显然有@types/save-svg-as-png支持原生 Angular 2+,但是当我尝试安装它时

npm install --save @types/save-svg-as-png
Run Code Online (Sandbox Code Playgroud)

找不到库 ( npm ERR! code 404)。

我用谷歌搜索了更多并在 github上遇到了这个问题,有人显然已经通过将它包含在 angular-cli.js 文件中来让它与 Angular 2 一起工作,但是随着对 Angular 的更改,这个文件在版本 7 中不再存在,我不知道现在需要怎么做。

我还发现了以下关于如何将 javascript 库集成到 Angular 2+ 中的文章,但其中大部分依赖于 @types 可用(它们不是,见上文)并且只有一个简短的部分关于如何提供你自己的库typings.d.ts文件,但玩了很长一段时间后,我没有进一步。是否有更详细的解释说明如何使用这种方法?

我还在stackoverflow 上找到了这篇关于如何将基于 IIFE 的库集成到打字稿应用程序中的文章,但没有让它工作。

我已将以下行添加到我的index.html文件中 …

javascript iife angular angular6 angular7

2
推荐指数
1
解决办法
4782
查看次数

将 IIFE 格式的函数导出到 ES6 模块

模块/IIFE 等有点麻烦。我有一个脚本,它曾经是一个 IIFE,并且使用了很多这个关键字等等。我正试图将它变成一个模块。

我有以下模块dice.js

export default function () {
this.createDice = function() { ... }
... 
}
Run Code Online (Sandbox Code Playgroud)

在主应用程序上,我称之为:

import Dice from "./dice.js";

let DICE = new Dice();
let dice1 = DICE.createDice();
let dice2 = DICE.createDice();
Run Code Online (Sandbox Code Playgroud)

它有效......我的问题是,有没有办法避免创建额外的 DICE 变量来调用所有方法?换句话说,我想这样称呼它:

import Dice from "./dice.js";

let dice1 = Dice.createDice();
let dice2 = Dice.createDice();
Run Code Online (Sandbox Code Playgroud)

我已经尝试过 IIFE,但无法解决问题。

javascript iife es6-modules

2
推荐指数
1
解决办法
843
查看次数

我可以在 useEffect 钩子周围使用 IIFE 吗?

我正在做一个有很多反模式的项目,我看到的是围绕多个 useEffects 的 IIFE,这是我所拥有的:

condition &&
      (() => {
        useEffect(() => {
          const calOffsetTimeout = setTimeout(() => {
            calcOffsetWidth();
          }, 150);
          return () => {
            clearTimeout(calOffsetTimeout);
          };
        }, [menuWidth.isExpanded, pdfWrapperRef.current]);

        useEffect(() => {
          calcOffsetWidth();
        }, [pdfWrapperRef, desiredScale, zooming]);

        useEffect(() => {
          calcOffsetWidth();
          return () => pdf && pdf.destroy();
        }, [pdf]);

        useEffect(() => {
          window.addEventListener('resize', calcOffsetWidth);

          return () => {
            window.removeEventListener('resize', calcOffsetWidth);
          };
        }, []);
      })();
Run Code Online (Sandbox Code Playgroud)

它正在工作,但缺点是我无法在这个 iife 函数中调试任何东西。我想知道将逻辑(尤其是钩子)包装到 iife 中是好是坏。我尝试的是在 deps 数组中添加条件,但是项目中的逻辑太多,一切都停止工作,所以这不是正确的决定。

javascript iife reactjs react-hooks

2
推荐指数
1
解决办法
69
查看次数

返回 setInterval 中使用的 IIFE 函数内部

setInterval( function returnval(){
  console.log('hello world');
  return returnval;
}(),2000);
Run Code Online (Sandbox Code Playgroud)

首先,请记住我是 javascript 新手。有人可以解释这段让我困惑的代码吗?当我们在匿名 setInterval 中包含的 IIFE 函数中返回函数名称时,实际上发生了什么?还要提前谢谢你。

javascript setinterval iife

2
推荐指数
1
解决办法
73
查看次数

为什么第二个console.log输出是函数体而不是20?

(function b() {
  console.log(b);
  b = 20;
  console.log(b);
})();
Run Code Online (Sandbox Code Playgroud)

我写了这个 JavaScript IIFE。
第一个console.log记录函数体。
然后b使用 value 创建变量20
第二个console.log还记录函数体。
为什么不20

javascript iife

2
推荐指数
1
解决办法
66
查看次数

IIFE内部的功能无法识别

我有一个IIFE,我试图制作一个书签.我希望弹出书签的模式会有一些调用函数的按钮.但是,当我有这样的结构时:

(function(){

   var __myFn = function(str){ //also have tried function __myFn(){..}
      alert(str);
   }

   //some AJAX that builds HTML with the `result`s

   document.getElementById("resultDiv").innerHTML = "<span onclick='__myFn(" + result.someData+ ")'>test</span>


}());
Run Code Online (Sandbox Code Playgroud)

我明白了 Uncaught ReferenceError: __myFn is not defined

如何识别此功能?还有另外一种方法吗?

javascript ajax closures iife

1
推荐指数
1
解决办法
761
查看次数

TypeError:无法读取未定义的属性"getAccounts"

我正在关注John Papa的Angular Style指南来创建一个小应用程序,我似乎无法解决controller使用a service...中的方法的问题.

(function () {
    'use strict';
    var accountsApp = angular.module('accountsApp', ['ui.bootstrap', 'ngAnimate']);
})();
Run Code Online (Sandbox Code Playgroud)

调节器

(function() {
    'use strict';

    angular
        .module('accountsApp')
        .controller('accountsCtrl', accountsCtrl);

    accountsCtrl.$inject = ['$log'];

    function accountsCtrl($log, accountsDataSvc) {
        /* jshint validthis:true */
        var vm = this;
        vm.title = 'Accounts';
        vm.accounts = [];
        vm.accountForm = null;
        vm.account = { id: 0, name: '', description: '' }

        activate();

        function activate() {
            return getAccounts(1).then(function() {
                $log.info('Accounts loaded');
            });
        }

        function getAccounts(id) {
            return accountsDataSvc.getAccounts(id).then(function(data) { …
Run Code Online (Sandbox Code Playgroud)

javascript dependency-injection iife angularjs

1
推荐指数
1
解决办法
301
查看次数