Javascript OOP 和 jQuery 无法触及对象属性

标签 javascript jquery oop

如何从 jquery 中编辑属性变量,如下例所示:

function Timetable(){
    this.timetables=[];
    //get timetable data for currentUser
     $.get('http://someurl.com/api',function(data){
         this.timetables.concat($.parseJSON(data));
    });
}

似乎发生的情况是 this.timetables 似乎超出了变量范围。

最佳答案

您不需要使用this,您需要创建一个closure .

function timetable(){

  // create a closure
  var timetables = Array();

  //get timetable data for currentUser
  $.get('http://someurl.com/api',function(data){

    // this references the Array created above
    that.timetables = that.timetables.concat($.parseJSON(data));
  });
}

我刚刚想到您可能正在使用timetable来创建对象。附带说明一下,如果是这种情况,为了清楚起见,惯例将其称为 Timetable。如果是这种情况,请使用类似的东西。

function Timetable () {

  // store a reference to the scope
  var that = this;

  // create an instance property of the Timetable object
  this.timetables = [];

  $.get('http://someurl.com/api',function(data){

    // use our scope reference captured above
    // to update the timetables property
    that.timetables = that.timetables.concat($.parseJSON(data));
  }); 
}

var t = new Timetable();

// once the get call is complete
console.log(t.timetables);

关于Javascript OOP 和 jQuery 无法触及对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518849/

相关文章:

javascript - JavaScript 导出语法之间有什么区别?

python - @staticmethod 和@classmethod 如何作用于python 中的变量?

PHP:将静态属性范围限制为特定类

javascript - 用于循环显示/隐藏复选框和列表的 Jquery 函数

javascript - 获取页面上的所有元素并在过滤器上隐藏它们

javascript - Selectize.js 加载回调传递到自定义函数

jquery - 如何从元素中获取字体样式(字体系列)

Javascript - 跟随链接,复制 URL 并更改原件?

java - 在 3 层 Entity-Repository-Service 应用程序中应该在哪里进行验证?

javascript - 在 forEach() 中创建方法;