[英]Calling a method from inside of another class
I have a node class like this: 我有一个这样的节点类:
var Classes = function () {
};
Classes.prototype.methodOne = function () {
//do something
};
when i want to call methodOne
, i use this: 当我想调用
methodOne
,我使用这个:
this. methodOne();
And it works. 它有效。 But right now i have to call it from inside of another method of another class.
但是现在我必须从另一个类的另一个方法中调用它。 This time its not works and cant access to
methodOne
: 这次它不起作用,无法访问
methodOne
:
var mongoose = new Mongoose();
mongoose.save(function (err, coll) {
//save to database
this. methodOne(); //this does not work
}
how i can call methodOne? 我该如何调用methodOne? i use
Classes.methodOne()
but it's not work 我使用
Classes.methodOne()
但它不起作用
this
inside the save
callback is in a new context and is a different this
than the outside one. this
里面save
的回调是在一个新的环境和是不同的this
比外面之一。 Preserve it in a variable where it has access to methodOne
在可以访问
methodOne
的变量中保留它
var that = this;
mongoose.save(function (err, coll) {
//save to database
that.methodOne();
}
You need to create variable outside of mongoose function. 你需要在mongoose函数之外创建变量。
var self = this;
var mongoose = new Mongoose();
mongoose.save(function (err, coll) {
//save to database
self.methodOne(); //If you call `this` from here, This will refer to `mongoose` class
}
If you are in an environment that works with ES6 you can use the Arrow expression : 如果您所处的环境适用于ES6,则可以使用箭头表达式 :
var mongoose = new Mongoose();
mongoose.save((err, col) => {
//save to database
this.methodOne();
})
What you can do is create an object of class Classes inside your other class and refer that method using this object: Ex: 你可以做的是在你的另一个类中创建一个类Classes的对象,并使用这个对象引用该方法:Ex:
var objClasses;
var mongoose = new Mongoose();
mongoose.save(function (err, coll) {
//save to database
objClasses = new Classes();
objClasses. methodOne(); //this should work
}
If it doesn't work please explain what exactly you want to achieve. 如果它不起作用,请解释您想要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.