2015-06-30 50 views
3

內部調用一個方法我有一個節點類是這樣的:從另一個類

var Classes = function() { 
}; 

Classes.prototype.methodOne = function() { 
    //do something 
}; 
時,我想打電話給 methodOne

,我用這個:

this. methodOne(); 

和它的作品。但是現在我必須從另一個課程的另一種方法中調用它。這一次,它不是作品和無法訪問methodOne

var mongoose = new Mongoose(); 
mongoose.save(function (err, coll) { 
    //save to database 
    this. methodOne(); //this does not work 
} 

我怎麼可以叫methodOne?我使用Classes.methodOne()但它不能正常工作

+1

這是指貓鼬類 –

+0

@wZVanG:是的,但我想訪問主類 – Fcoder

回答

5

thissave回調是在新的上下文,是一個不同的this比外面之一。 保留它在一個變量,其中它可以訪問methodOne

var that = this; 
mongoose.save(function (err, coll) { 
    //save to database 
    that.methodOne(); 
} 
2

您需要創建貓鼬功能的變量之外。

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 
} 

如果你是在與ES6工作的環境中,你可以使用Arrow expression

var mongoose = new Mongoose(); 
mongoose.save((err, col) => { 
    //save to database 
    this.methodOne(); 
}) 
2

你可以做的是創造類的類的對象的其他類中,並指這使用此對象的方法:例如:

var objClasses; 
var mongoose = new Mongoose(); 
mongoose.save(function (err, coll) { 
    //save to database 
objClasses = new Classes(); 
    objClasses. methodOne(); //this should work 
} 

如果它不起作用,請解釋您要達到的目標。