1

在 nodejs 中使用 superagent 包,我不确定我可以在 .end() 中做什么。

在“get”函数中获取数据后,我试图更改“title”和“description”的值,但它们保持不变。

另外,当我尝试在 .end() 中返回 data.body[0].title 时,然后

var todo = new Todo();
console.log(todo.get());

它说它是未定义的。如何使用 superagent 语法更改 Todo 属性的值?

代码如下:

function Todo() {
  this.title = "milk";
  this.description = "ok, Milk is a white liquid produced by the mammary glands of mammals.";
}

util.inherits(Todo, Model);

Todo.prototype.get = function() {
  console.log(this.title);
  request
    .get(this.read().origin + '/todos/11' + '?userId=1&accessToken=' + this.read().accessToken)
    .send({
      username : 'jiayang',
      password : 'password',
      clientId : this.read().clientId,
      clientSecret : this.read().clientSecret
    })
    .end(function(data) {
      console.log(data.body[0]);
      this.title = data.body[0].title;
      this.description = data.body[0].description;
    });
};
4

1 回答 1

1

回调中的上下文thisend回调函数的本地范围。

尝试;

Todo.prototype.get = function() {
  var self = this;

  console.log(this.title);
  request
    .get(this.read().origin + '/todos/11' + '?userId=1&accessToken=' + this.read().accessToken)
    .send({
      username : 'jiayang',
      password : 'password',
      clientId : this.read().clientId,
      clientSecret : this.read().clientSecret
    })
    .end(function(data) {
      console.log(data.body[0]);
      self.title = data.body[0].title;
      self.description = data.body[0].description;
    });
};
于 2014-05-29T07:27:04.880 回答