在这种情况下如何绑定到正确的对象?

时间:2015-01-01 02:39:56

标签: javascript prototype this

我的问题是如何正确地指出这个'到最后2行的右边对象。我理解'这个'现在指向窗口。如何纠正它们。

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"

3 个答案:

答案 0 :(得分:2)

重构您的时间功能如下:

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/

答案 1 :(得分:1)

您可以使用Function.prototype.bind,就像Josh的建议(需要IE9及以上版本):

times(3, christophe.greet.bind(christophe), elodie);
times(1, elodie.getFullName.bind(elodie));

IE8还有一个bind polyfill - 。

或者,您可以使用Function.prototype.call,您需要修改times功能:

function times(n, fx, subjective, objective) {
    for (var index = 0; index < n; ++index) {
        fx.call(subjective, objective);
    }
}

times(3, christophe.greet, christophe, elodie);
times(1, elodie.getFullName, elodie);

答案 2 :(得分:0)

你可以这样做,

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, self, arg) {
    for (var index = 0; index < n; ++index) {
        fx.call(self,arg);
    }
}
times(3, christophe.greet, christophe , elodie); 
times(1, elodie.getFullName, christophe );