我尝试在函数运行后控制变量fullName,但它没有更改值,只是控制台默认值未设置,为什么会这样?
function Test() { this.clientData = { fullName : "Not Set",setUserName: function (firstName,lastName) { this.fullName = firstName + " " + lastName; },getUserInput2: function (firstName,lastName,callback) { callback(firstName,lastName); } }; this.getUserInput1 = function (firstName,callback) { callback(firstName,lastName); }; } var test = new Test(); test.getUserInput1("A1","B1",test.clientData.setUserName); console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set //expected => A1 B1 test.clientData.getUserInput2("A2","B2",test.clientData.setUserName); console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set //expected => A2 B2
解决方法
这很有效.你可以不使用bind()函数来做到这一点.你只需要将Test对象存储在变量中.
function Test() { var t = this this.clientData = { fullName : "Not Set",lastName) { t.clientData.fullName = firstName + " " + lastName; },callback) { callback(firstName,lastName); } }; this.getUserInput1 = function (firstName,callback) { callback(firstName,lastName); }; } var test = new Test(); test.getUserInput1("A1",test.clientData.setUserName); console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set //expected => A1 B1 test.clientData.getUserInput2("A2",test.clientData.setUserName); console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set