【问题标题】:How to create a object/function with defined setting when create new?新建时如何创建具有定义设置的对象/函数?
【发布时间】:2013-08-15 08:12:14
【问题描述】:

我想做这样的事情:

function Student (id, class) {
  var id = id
  var class = class

  this.get = function (subject) {
    $.ajax({
      url: 'myurl',
      data: { id: id, class: class, subject: subject },
      success: function (r) { return r }
    })
  }
  this.set = function (subject, mark) {
    $.ajax({
      url: 'myurl',
      method: 'post',
      data: { id: id, class: class, subject: subject, mark: mark },
      success: function (r) { return r }
    })
  }
}

我的问题是如何修改我的函数以便我可以创建新学生如下

var s1 = new Student (22, 4) // to set predefined id & class

但是,我想要 set 和 get 如下(如 jquery set & get)

s1("math") // to get 
s1("history", 70) // to set

**

所以我认为答案不可能作为一个对象来存储属性 id 和类并像没有函数名的函数一样调用。谢谢你们的回答。

**

【问题讨论】:

标签: javascript


【解决方案1】:
  1. 您可以检查调用者提供了多少参数。或者检查未定义的值。

    function test(a, b) {
      // both ifs check b was not provided
      if (typeof b === "undefined") {
      }
      if (arguments.length == 1) {
      }
    }
    
  2. 您当前的函数可能无法工作,因为您正在从回调中返回。 AJAX(在大多数情况下)是异步的。因此,在您的情况下,您必须添加另一个参数来提供回调。

    this.get = function (subject, callback) {
      $.ajax({
        url: 'myurl',
        data: { id: id, class: class, subject: subject },
        success: function (r) { callback(r); }
      })
    }
    

仅供参考,class 是 ECMAScript 规范的保留关键字。

【讨论】:

  • 另一种获取所提供参数数量的方法是arguments.length。也许是一个更好的解决方案。
【解决方案2】:
function sample(x,y){
id=x;
subjectClass =y;
if(arguments.length == 1){
//getter
}
else{
//setter
}
}

调用getter

sample("maths")

调用设置器

sample("history",70);

注意:

class是保留关键字,所以请去掉它,你可以使用其他变量名

【讨论】:

    【解决方案3】:

    但是,我想要的设置如下

    这意味着s1 将是一个函数,而不是Student 实例。所以你的构造函数需要返回它。

    function student(id, klass) {
        // no need to declare variables here that are parameters already
        return function(subject, mark) {
            var data = {id: id, class: klass, subject: subject},
                opt = {url: 'myurl', data: data};
            if (arguments.length > 1) { // something was given to `mark`
                data.mark = mark;
                opt.method = "post";
            }
            return $.ajax(opt);
        };
    }
    

    顺便说一句,由于你不能return the response from an ajax call,函数将返回 jqXHR 承诺:

    var s1 = student(22, 4); // `new` is unnecessary now
    s1("math").then(function(r) { console.log("got maths result:", r); });
    s1("history", 70).then(function(r) { console.log("successfully set marks"); });
    

    【讨论】:

      猜你喜欢
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 2020-09-13
      • 2021-04-06
      • 2015-11-14
      相关资源
      最近更新 更多