看mongoose文档对实例方法里面的this有个疑问。麻烦大家一下
发布于 8 年前 作者 wszgxa 3375 次浏览 来自 问答
var animalSchema = new Schema({ name: String, type: String });

animalSchema.methods.findSimilarTypes = function(cb) {
  return this.model('Animal').find({ type: this.type }, cb);
};

调用:

var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });

dog.findSimilarTypes(function(err, dogs) {
  console.log(dogs); // woof
});

这段return this.model('Animal').find({ type: this.type }, cb);

这里有两个this,我理解的是这个this是animalSchema,但是后面的type: this.type。这个type分明是dog这个实例。

有些疑惑,请教下。

6 回复

@wszgxa this 算是魔法变量吧,根据你调用函数的方法会绑定不一样的值。可以看一下这个 Javascript的this用法

@IchiNiNiIchi this的用法我还是知道的。。。

这里的this应该是指向animalSchema,但是他能够获取的实例dog里面的type,里面是不是有啥继承关系之类的。

new 的时候, 将animal的方法都绑定一份给dog了, 所以this.type是dog, 我是这样理解的

@wszgxa 为什么觉得 this 应该指向 animalSchema 呢? 这里是这么调用的,dog.findSimilarTypes,明显 this 是绑定 dog 的。

@IchiNiNiIchi thanks,对着的。

回到顶部