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!');
});
};
});
当我调用 callBstApi(myParams) onload 时,它可以工作,但是如果我从我的浏览器控制台调用该函数,它会显示以下错误
我必须在 vanilla js 中编写脚本。
进一步扩展我的评论:callBstApi
在您的控制台中不可用的原因是因为它不存在于全局范围内。该函数在您的 ready
函数中定义,因此无法访问。为了避免这种情况,您需要将该方法公开给全局 window 范围。这可以通过这样做来完成:
window.callBstApi = ...
您现在可以在全局范围内访问 callBstApi
(带或不带 window.
前缀,这是完全可选的)并这样调用它:
callBstApi(myParams);
// If you want to be pedantic, you can do:
window.callBstApi(myParams);
p/s:唯一的风险是,如果该键已在 window
对象中找到,您将覆盖其中的任何内容。
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!');
});
};
});
当我调用 callBstApi(myParams) onload 时,它可以工作,但是如果我从我的浏览器控制台调用该函数,它会显示以下错误
我必须在 vanilla js 中编写脚本。
进一步扩展我的评论:callBstApi
在您的控制台中不可用的原因是因为它不存在于全局范围内。该函数在您的 ready
函数中定义,因此无法访问。为了避免这种情况,您需要将该方法公开给全局 window 范围。这可以通过这样做来完成:
window.callBstApi = ...
您现在可以在全局范围内访问 callBstApi
(带或不带 window.
前缀,这是完全可选的)并这样调用它:
callBstApi(myParams);
// If you want to be pedantic, you can do:
window.callBstApi(myParams);
p/s:唯一的风险是,如果该键已在 window
对象中找到,您将覆盖其中的任何内容。