回调无法正常工作。需要返回object属性值

时间:2016-06-07 18:45:36

标签: javascript node.js callback

var studentMarks = {
    mathScore : 0,
    englishScore : 0,
    totalScore : null,
    computeMarks : function (mathScore, englishScore) {
        this.mathScore = mathScore;
        this.englishScore = englishScore;
        this.totalScore = this.mathScore + this.englishScore;
        console.log(this.totalScore);
    }
}

function setStudentScore(score1,score2,callback){
    callback(score1,score2);
}

setStudentScore(40,50,studentMarks.computeMarks);
print(studentMarks.totalScore);  //prints 'undefined'

print语句应该打印90而不是打印undefined。我应该对computeMarks方法做些什么改变?

5 个答案:

答案 0 :(得分:2)

setStudentScore(40,50,studentMarks.computeMarks);

这里只传递computeMarks值作为回调。它是一个函数,而不是原始对象方法。没有关于此功能相关的对象的信息。

当它被调用时,this将指向全局对象。

尝试直接绑定上下文:

setStudentScore(40,50,studentMarks.computeMarks.bind(studentMarks));

答案 1 :(得分:2)

尝试

setStudentScore(40,50,studentMarks.computeMarks.bind(studentMarks));

在JS中,称之为“拥有”JavaScript代码的对象。在你的情况下,看起来它是调用它的函数。您可以使用bind来告诉它在您的上下文中引用了什么。 Read this if you want

答案 2 :(得分:0)

这应该对你有用

var studentMarks = {
    mathScore : 0,
    englishScore : 0,
    totalScore : null,
    computeMarks : function (mathScore, englishScore) {
        this.mathScore = mathScore;
        this.englishScore = englishScore;
        this.totalScore = this.mathScore + this.englishScore;
    }.bind(studentMarks)
}

function setStudentScore(score1,score2,callback){
    callback(score1,score2);
}

setStudentScore(40,50,studentMarks.computeMarks);

在控制台中工作

答案 3 :(得分:0)

试试这个:

 var studentMarks = function() {
 var self = this;
 this.mathScore = 0;
 this. englishScore = 0;
 this.totalScore = null;
 this.computeMarks = function (mathScore, englishScore) {
  self.mathScore = mathScore;
  self.englishScore = englishScore;
  self.totalScore = this.mathScore + this.englishScore;
  console.log(self.totalScore);
 }
};

function setStudentScore(score1,score2,callback){
callback(score1,score2);
}

var obj = new studentMarks();

setStudentScore(40,50,obj.computeMarks);
console.log(obj.totalScore);  //prints 90

答案 4 :(得分:0)

你可以这样做



var studentMarks = {
    mathScore : 0,
    englishScore : 0,
    totalScore : null,
    computeMarks : function (mathScore, englishScore) {
        this.mathScore = mathScore;
        this.englishScore = englishScore;
        this.totalScore = this.mathScore + this.englishScore;
        return this.totalScore;
    }
};

function setStudentScore(score1,score2,callback){
    callback(score1,score2);
}

setStudentScore(40,50,function(a,b){studentMarks.computeMarks(a,b)});
console.log(studentMarks.totalScore);