实例函数变量没有改变?

Dav*_*pan 6 javascript

我尝试在函数运行后控制变量fullName,但它没有更改值,只是控制台默认值Not Set,为什么会这样?

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, lastName, 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
Run Code Online (Sandbox Code Playgroud)

Hir*_*tel 3

这是有效的。您可以在不使用bind()函数的情况下执行此操作。您只需将 Test 对象存储在变量中即可。

function Test() {
 var t = this
 this.clientData = {
          fullName : "Not Set",
          setUserName: function (firstName, lastName) {
          t.clientData.fullName = firstName + " " + lastName;
          },
          getUserInput2: function (firstName, lastName, callback) {
              callback(firstName, lastName);
          }
       };
 this.getUserInput1 = function (firstName, lastName, 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
   
Run Code Online (Sandbox Code Playgroud)