简体   繁体   English

从浏览器控制台调用时未定义 Javascript 函数

[英]Javascript function not defined when call from browser console

var ready = function ready(callback) {
      if (document.readyState != "loading") callback();else document.addEventListener("DOMContentLoaded", callback);
    };
    ready(function () {
      "use strict"; 
      var callBstApi = function callBstApi(params) {
        fetch("http://localhost:3000/api/v1/myApi", {
          method: 'POST',
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(params)
        }).then(function (data) {
          console.log(JSON.stringify(params));
        }).catch(function (error) {
          console.log('test is cancelled!');
        });
      };
    });
    

When I call callBstApi(myParams) onload it works but if I call that function from my browser console it shows below error当我调用 callBstApi(myParams) onload 时,它可以工作,但是如果我从浏览器控制台调用该函数,它会显示以下错误错误!!!

I have to write script in vanilla js.我必须用香草 js 编写脚本。

To further extend on my comment: the reason why callBstApi is not available in your console is because it is not present in the global scope.进一步扩展我的评论: callBstApi在您的控制台中不可用的原因是因为它不存在于全局范围内。 The function is defined inside your ready function and is therefore inaccessible.该函数是在您的ready函数中定义的,因此无法访问。 To circumvent this, you will want to expose the method to the global window scope.为了避免这种情况,您需要将该方法公开给全局窗口范围。 This can be done by doing so:这可以通过这样做来完成:

window.callBstApi = ...

You can now access callBstApi in the global scope (with or without the window. prefix, that is completely optional) and invoke it as such:您现在可以在全局范围内访问callBstApi (带或不带window.前缀,这是完全可选的)并像这样调用它:

callBstApi(myParams);

// If you want to be pedantic, you can do:
window.callBstApi(myParams);

p/s: The only risk is that you'll overwrite whatever that's there, if that key is already found in the window object. p/s:唯一的风险是您将覆盖那里的任何内容,如果该键已在window对象中找到。

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

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