CNode

看mongoose文档对实例方法里面的this有个疑问。麻烦大家一下

问答
Wwszgxa发布于10 年前最后回复10 年前6 回复4284 浏览0 收藏
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)

W
wszgxa#1·10 年前

up

I
IchiNiNiIchi#2·10 年前
引用 wszgxaup

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

W
wszgxa#3·10 年前
引用 IchiNiNiIchi@wszgxa this 算是魔法变量吧,根据你调用函数的方法会绑定不一样的值。可以看一下这个 Javascript的this用法

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

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

O
o6875461#4·10 年前

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

I
IchiNiNiIchi#5·10 年前
引用 wszgxa@IchiNiNiIchi this的用法我还是知道的。。。 这里的this应该是指向animalSchema,但是他能够获取的实例dog里面的type,里面是不是有啥继承关系之类的。

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

参与回复
登录后即可参与回复。登录