javascript – 实例函数变量没有改变?

前端之家收集整理的这篇文章主要介绍了javascript – 实例函数变量没有改变?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试在函数运行后控制变量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
原文链接:https://www.f2er.com/js/150710.html

猜你在找的JavaScript相关文章