所以我有一些具有以下(伪)结构的javascript。我如何从this.last_updated函数设置父函数的showUpdates变量,而无需专门引用名称分配(my_main_function)。

var my_main_function = new main()

function main() {
 this.last_updated;

 function showUpdates(data){
 //set this.last_updated=

 // do Stuff
 }
 this.updateMain(){
  $.ajax({
                 url:"/my_url/"
                 type:"POST",
                 datatype:"json",
                 data: {'last_updated':this.last_updated },
                 success : function(data) { showUpdates(data)},
                 error : function(xhr,errmsg,err) {
                 alert(xhr.status + ": " + xhr.responseText); },
    });
 }
}

最佳答案

更新了代码库一的注释:

有两种创建对象的方法。

如果您需要多次创建对象,则可以这样做:

var YourDefintinon = function() {
};

YourDefintinon.prototype.foo = function() {

};

obj1 = new YourDefintinon();
obj2 = new YourDefintinon();

obj1.foo();


如果在代码中只需要一次,则可以这样:

var obj = {

};

obj.foo = function() {

};

foo();


因此,仅在代码如下所示时,您才需要main
使用Function.prototype.bind(对于较旧的浏览器,使用polyfill及其)将showUpdates绑定到obj

var main = {
  last_updated : null
};

function showUpdates(data){
  this.last_updated = data.update_time;
}

main.updateMain = function () {
  //<< bind showUpdates  to `this` and save the bound function in the local variabel showUpdates
  var showUpdates = showUpdates.bind(this);

  $.ajax({
     url:"/my_url/"
     type:"POST",
     datatype:"json",
     data: {'last_updated':last_updated },
     success : showUpdates, //<< uses the showUpdates variable not the function
     error : function(xhr,errmsg,err) {
       alert(xhr.status + ": " + xhr.responseText);
     },
  });
};


由于您不想让其他人访问showUpdates,因此可以将整个块包装到一个立即调用的函数中:

var main = (function() {
  var main = {
    last_updated : null
  };

  function showUpdates(data){
    this.last_updated = data.update_time;
  }

  main.updateMain = function () {
    var showUpdates = showUpdates.bind(this);

    $.ajax({
       url:"/my_url/"
       type:"POST",
       datatype:"json",
       data: {'last_updated':last_updated },
       success : showUpdates,
       error : function(xhr,errmsg,err) {
         alert(xhr.status + ": " + xhr.responseText);
       },
    });
  };

  return main;
}());

10-08 19:04