繁体   English   中英

如何将初始参数传递给javascript函数

[英]How to pass initial arguments to javascript functions

我有一些简单的javascript函数可与此类API进行交互以登录:

    login: function(username, password) {
    var calledUrl = baseapi + "user/login/" + credentials;
    calledUrl.post(
        function (content) {
            /*console.log("success" + JSON.stringify(content, null, 4));*/
        },
        function (e) {
            console.log("it failed! -> " + e);
        },
        {
            "username": username,
            "password": password

        },
        {"Accept" : "application/json"}
    );
},

问题是,我必须在URL中传递一些凭据,它们看起来像这样:

var credentials = "?api_username=" + api_username + "&api_key=" + api_key;

现在,此变量已经过硬编码,可以进行一些测试,但是当然应该为使用该函数的每个人对其进行更改。 我不想在每次请求时都询问它,在这种情况下,我只想询问usernamepassword 我想在初始化过程中一劳永逸地索要它,无论它叫什么,然后在执行各种功能时记住它。

如果.login()是通常需要凭据的第一个方法,则可以将其设为该方法的必需参数,然后将凭据存储在对象中:

login: function(username, password, credentials) {
    // save credentials for use in other methods    
    this.credentials = credentials;
    var calledUrl = baseapi + "user/login/" + credentials;
    calledUrl.post(
        function (content) {
            /*console.log("success" + JSON.stringify(content, null, 4));*/
        },
        function (e) {
            console.log("it failed! -> " + e);
        },
        {
            "username": username,
            "password": password

        },
        {"Accept" : "application/json"}
    );
},

然后,在其他方法中,您可以使用this.credentials访问该用户的凭据。

如果还有其他方法也可能首先被调用并且需要它们的凭据,那么您可以将凭据也用作这些凭据的参数,或者可以创建仅建立凭据的.init()方法,也可以使其此对象的构造函数中的一个参数。


您可能还必须修复此行:

 calledUrl.post(...)

因为calledUrl是一个字符串,并且字符串没有.post()方法,除非您使用某种添加了一个的第三方库。

我建议您阅读有关JavaScript范围的内容。 如果没有更多关于您要做什么的解释,我会尝试这种模式...

var app = {
  baseapi: 'http://some.url.com'

  /* assuming the api user/pass are different form the account trying to log in */
  ,api_username: ''
  ,api_key: ''

  ,username: ''
  ,userpass: ''

  ,get_creditialString: function() {
    return '?api_username=' + this.api_username + '&api_key=' + this.api_key;
  }
  ,init: function(){    
    // do something to prompt for username and password
    this.username = 'myUserName';
    this.userpass = 'supersecretpassword';

    this.login();
  }
  ,login: function() {
    var calledUrl = this.baseapi + "user/login/" + this.get_credentialString();
    calledUrl.post(
        function (content) {
            /*console.log("success" + JSON.stringify(content, null, 4));*/
        },
        function (e) {
            console.log("it failed! -> " + e);
        },
        {
            "username": this.username,
            "password": this.userpass
        },
        {"Accept" : "application/json"}
    );
  }
}
app.init();

暂无
暂无

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

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