Javascript作用域和this.Variable

Javascript作用域和this.Variable,javascript,scope,Javascript,Scope,因此,我有一些javascript具有以下(伪)结构。如何从showUpdates函数中设置父函数的this.last\u updated变量,而不特别引用名称分配(my\u main\u函数) 更新了代码基注释之一: 创建对象有两种方法 如果需要多次创建对象,请按以下方式执行: var YourDefintinon = function() { }; YourDefintinon.prototype.foo = function() { }; obj1 = new YourDefinti

因此,我有一些javascript具有以下(伪)结构。如何从
showUpdates
函数中设置父函数的
this.last\u updated
变量,而不特别引用名称分配(
my\u main\u函数


更新了代码基注释之一:

创建对象有两种方法

如果需要多次创建对象,请按以下方式执行:

var YourDefintinon = function() {
};

YourDefintinon.prototype.foo = function() {

};

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

obj1.foo();
如果在代码中只需要一次,您可以这样做:

var obj = {

};

obj.foo = function() {

};

foo();
因此,只有当代码看起来像这样时,您才需要
main
: 使用(对于较旧的浏览器,使用its)将
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);
     },
  });
};

即使是伪代码,也应该确保它是干净的。
main
真的围绕着
showUpdates
updateMain
,为什么要写
var这个。main\u updated
this.updateMain
my_main_函数的一部分吗?如果调用它,将向
ajax
请求发出请求?我将更改var名称以使其更清楚-正如您将看到updateMain调用update函数,并将上次更新的时间戳传递给服务器。您对
有什么意思,但没有必要对于多个main()
?您只有一个主对象,下次不会执行新的主对象?如果是这样,您根本不需要
new main()
。我对javascript有点不习惯,我的印象是,将一个函数分配给一个var的目的是为了让您可以有多个实例,即var first_timer=new timer();var second_timer=新定时器();我猜没有默认声明的函数类型?因为如果我只需要一个timer()-那么为var和函数都指定一个名称似乎是非常多余的。请参阅。
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);
     },
  });
};
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;
}());