0

我有一个在创建对象之前定义的函数。此预定义函数使用“this”关键字来更改对象中属性的值。在对象内部,我有一个使用一个参数调用预定义方法的方法。但是,在调用此方法并尝试打印应该更改的属性的值之后,它仍然保持不变。我该如何解决?

var setName = function(yourName){
    this.name = "Your name is " + yourName;
};

// create an object called `human`
var human = {
    name: "Nothing here yet",
    setHumanName: function(name) {
        setName(name);//Name should be changed now
    }
};

human.setHumanName("Emeka");
console.log(human.name); //this does not print the new value of name
4

2 回答 2

2

您应该在对象上下文中调用该函数:

setHumanName: function(name) {
    setName.call(this, name);
}
于 2013-04-25T11:22:45.627 回答
1

只需使用

var human = {
    name: "Nothing here yet",
    setHumanName: setName // no invocation, only assigning the function
};

要在对象上显式调用任意函数(以便将它们的this关键字设置为该对象),请使用函数的call方法

于 2013-04-25T11:32:21.457 回答