回调引用作为Javascript中的参数

时间:2015-04-14 04:12:01

标签: javascript callback

var clientData = {
    id: 1969,
    fullName: "Not Set",
    setUserName: function (firstName, lastName)  {
      clientData.fullName = firstName + " " + lastName;
      console.log(clientData.fullName);
    }
};

function getUserInput(firstName, lastName, callback)  {  
  //why can't I say clientData.callback (firstName, lastName); instead
  callback (firstName, lastName);
}

getUserInput ("Peter", "Pan", clientData.setUserName);

正如代码中所评论的那样,为什么我不能说clientData.callback (firstName, lastName);如果回调参数引用应该可以从具有点访问权限的clientData访问的函数?如果clientData.setUserName只是对函数对象的引用,我不应该不小心用我的注释代码说clientData.clientData.setUsername,对吗?

我是初学者,因为它不起作用,我确定我在想错误。

3 个答案:

答案 0 :(得分:2)

clientData.callback 字面尝试访问callback上的属性clientData。考虑clientData.callback等同于clientData['callback']

.之后的内容未被视为变量。即使它是,callback的值是函数。您不能将函数用作属性名称。属性名称是字符串

答案 1 :(得分:2)

创建函数时,请将参数视为函数中使用的变量。当你这样做时:

function getUserInput(firstName, lastName, callback)

你打电话给:

getUserInput ("Peter", "Pan", clientData.setUserName);

函数顶部隐含的是:

var firstName = "Peter";
var lastName = "Pan";
var callback = clientData.setUserName

无论您传入的是什么callback,都会在函数内引用callback。因此,如果您传入clientData.setUserName,它属于名为clientData的对象并不重要 - 它仍然被称为callback

答案 2 :(得分:0)

尝试使用:

function getUserInput(firstName, lastName)  {  
  clientData.setUserName (firstName, lastName);
}