[英]Callback references as arguments in Javascript
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);
As is commented in the code, why can't I say clientData.callback (firstName, lastName);
如代码中所注释,为什么我不能说clientData.callback (firstName, lastName);
if what the callback argument is referencing is the function that should be accessible from clientData with dot access? 如果回调参数引用的是应该通过点访问从clientData访问的函数? If clientData.setUserName is just a reference to a function object, I shouldn't be accidentally saying clientData.clientData.setUsername with my commented code, right? 如果clientData.setUserName只是对函数对象的引用,那么我应该不带意外的代码说出clientData.clientData.setUsername对吧?
I'm a beginner, and because it's not working I'm sure I'm thinking of something wrong. 我是一个初学者,因为它无法正常工作,所以我确定我在想什么错误。
clientData.callback
would literally try to access property callback
on clientData
. clientData.callback
会从字面上尝试访问属性callback
的clientData
。 Think about clientData.callback
being equivalent to clientData['callback']
. 考虑一下clientData.callback
等同于clientData['callback']
。
What comes after the .
之后会发生什么.
is not treated as a variable. 不被视为变量。 Even if it were, the value of callback
is a function . 即使是, callback
的值也是一个function 。 You can't use a function as property name . 您不能将函数用作属性名称 。 Property names are strings . 属性名称是字符串 。
When you create a function, think of the arguments as variables used in the function. 创建函数时,请将参数视为函数中使用的变量。 When you do: 当您这样做时:
function getUserInput(firstName, lastName, callback)
and you call it with: 然后用以下命令调用它:
getUserInput ("Peter", "Pan", clientData.setUserName);
What implicitly happens at the top of the function is: 函数顶部隐式发生的是:
var firstName = "Peter";
var lastName = "Pan";
var callback = clientData.setUserName
Whatever you pass in as callback
is referenced inside the function as callback
. 您作为callback
传递的任何内容在函数内部都称为callback
。 So if you pass in clientData.setUserName
, it doesn't matter that it belongs to an object called clientData
- it is still referred to as callback
inside. 因此,如果传入clientData.setUserName
,则它属于名为clientData
的对象并不重要-它仍称为内部callback
。
Try using: 尝试使用:
function getUserInput(firstName, lastName) {
clientData.setUserName (firstName, lastName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.