如何访问此JavaScript函数中的变量永久链接?

时间:2019-03-10 05:14:25

标签: javascript

好的,我有这个函数,我需要使用permalink访问名为console.log()的变量的内容 但我不明白 我跳到未定义变量永久链接。但是当我带走的时候!的!功能 如果我可以访问permalink,这是我的新手,谢谢您的帮助和评论,这可能对我有用。 我不需要编辑功能就可以这样做,因为它来自外部 这是我的代码。

!function(PriTwo, document) {
  var DocumentProtocol =
    document.location.protocol != 'https:' &&
    document.location.protocol != 'http:'
      ? 'https:'
      : document.location.protocol;
  var permalink = DocumentProtocol + '//google.com';
  var permalink_two = DocumentProtocol + '//facebook.com';
};

console.log(permalink);

我需要console.log在函数外面,不能在里面。 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您已经创建了立即调用函数表达式(IIFE),但是,您最后并未添加括号,因此尚未调用函数。有关IIFE read this.

的更多信息

此外,您无法访问在需要将permalink指定为全局变量的函数中声明的局部变量。这是link for a scope in js

有关自执行匿名功能click here的更多信息。 试试这个。

    var permalink='';
    var permalink_two='';
    !(function() {
    console.log('dd');
    var DocumentProtocol =
        document.location.protocol != 'https:' &&
        document.location.protocol != 'http:'
          ? 'https:'
          : document.location.protocol;
          console.log('a');
      permalink = DocumentProtocol + '//google.com';
      permalink_two = DocumentProtocol + '//facebook.com';
     
    })();

    console.log(permalink);
    console.log(permalink_two);

或者您可以从简单函数内部返回数组,然后使用键访问数组。

function PriTwo() {
            var DocumentProtocol = (document.location.protocol != "https:" && document.location.protocol != "http:") ? "https:" : document.location.protocol;
            var permalink=[];
            permalink.push(DocumentProtocol + '//google.com');
            permalink.push(DocumentProtocol + '//facebook.com');
             return permalink;
   }
  var link = PriTwo();
  console.log(link[0]);
  console.log(link[1]);