我的问题是如何正确地将“ this”指向最后两行的正确对象。我了解“此”现在指向窗口。如何纠正它们正确的。

function Person(first, last, age) {
    this.first = first;
    this.last = last;
    this.age = age;
}
Person.prototype = {
    getFullName: function() {
        alert(this.first + ' ' + this.last);
    },
    greet: function(other) {
        alert("Hi " + other.first + ", I'm " + this.first + ".");
    }
};
var elodie = new Person('Elodie', 'Jaubert', 27);
var christophe = new Person('Christophe', 'Porteneuve', 30);

function times(n, fx, arg) {
    for (var index = 0; index < n; ++index) {
        fx(arg);
    }
}
times(3, christophe.greet, elodie); // => Three times "Hi Elodie, I'm undefined."
times(1, elodie.getFullName ); // => "undefined undefined"

最佳答案

像这样重构您的时间功能:

function times(n, obj, fx, arg) {
    for (var index = 0; index < n; ++index) {
        obj[fx](arg);
    }
}
times(3, christophe, "greet", elodie);
times(1, elodie, "getFullName" );


工作提琴:

http://jsfiddle.net/acatkk53/

07-24 16:31