简体   繁体   English

Javascript变量范围问题

[英]Issue with Javascript Variable Scope

I have a variable mutedUser which I would like to have persist to another function. 我有一个变量mutedUser,我想坚持到另一个函数。 I am having a bit of trouble with the variable persisting outside the click event. 我在click事件之外持久存在变量时遇到了一些麻烦。 What would be the best way to have it so the "return mutedUser" would keep the "muted" string addition based on the conditions of the if statement being met? 拥有它的最佳方法是什么,以便“返回mutedUser”将根据if语句的条件保持“静音”字符串添加? Thanks! 谢谢!

*The console.log's were me checking to see where the persistance stops * console.log是我检查持久性停止的位置

this.isUserMuted = function isUserMuted(payload) {
  var mutedUser = '';
  // If mute button is clicked place them into muted users list
  // check for duplicates in list
  $("#messages-wrapper").off('click', '.message button.muteButton');
  $("#messages-wrapper").on('click', '.message button.muteButton', function(e) {

      $('#unMute').show();

      //create userId reference variable
      var chatUserID = parseInt($(this).parent().parent().attr("data-type"));

      //store userId in muted user object
      mutedUsers[chatUserID] = {};
      mutedUsers[chatUserID].id = chatUserID;
      mutedUsers[chatUserID].muted = true;

      if (mutedUsers[chatUserID] !== null && mutedUsers[chatUserID].id === payload.a) {
          console.log("user is now muted");
          mutedUser += ' muted';
          console.log(mutedUser + 1);
      }
      console.log(mutedUser + 2);
  });
  return mutedUser;
};

If I understood what you're trying to do (by looking at the code), this would be the best approach: 如果我理解你要做的事情(通过查看代码),这将是最好的方法:

// If mute button is clicked place them into muted users list
// check for duplicates in list
$("#messages-wrapper").off('click', '.message button.muteButton');
$("#messages-wrapper").on('click', '.message button.muteButton', function(e) {
    $('#unMute').show();

    //create userId reference variable
    var chatUserID = parseInt($(this).parent().parent().attr("data-type"));

    //store userId in muted user object
    mutedUsers[chatUserID] = {};
    mutedUsers[chatUserID].id = chatUserID;
    mutedUsers[chatUserID].muted = true;
});

this.isUserMuted = function isUserMuted(payload) {
  var mutedUser = '';

  if (mutedUsers[payload.a] !== null) {
      mutedUser += ' muted';
  }

  return mutedUser;
};

The code retains the array of mutedUsers , and isUserMuted function checks if provided user is in that array. 代码保留mutedUsers数组, isUserMuted函数检查提供的用户是否在该数组中。 In the code you provided, you would attach a new event handler every time isUserMuted function is called.. 在您提供的代码中,每次调用isUserMuted函数时都会附加一个新的事件处理程序。

The isUserMuted function could even be shortened to: isUserMuted函数甚至可以缩短为:

this.isUserMuted = function isUserMuted(payload) {
  return mutedUsers[payload.a] !== null ? ' muted' : '';
};

Edit 编辑

Sorry, my mistake. 抱歉,是我的错。 Another way is to pass in that variable, ie 另一种方法是传入该变量,即

this.isUserMuted = function isUserMuted(payload, isMuted) {
  isMuted = '';
  // If mute button is clicked place them into muted users list
  // check for duplicates in list
  $("#messages-wrapper").off('click', '.message button.muteButton');
  $("#messages-wrapper").on('click', '.message button.muteButton', function(e) {

      $('#unMute').show();

      //create userId reference variable
      var chatUserID = parseInt($(this).parent().parent().attr("data-type"));

      //store userId in muted user object
      mutedUsers[chatUserID] = {};
      mutedUsers[chatUserID].id = chatUserID;
      mutedUsers[chatUserID].muted = true;

      if (mutedUsers[chatUserID] !== null && mutedUsers[chatUserID].id === payload.a) {
          console.log("user is now muted");
          isMuted += ' muted';
          console.log(mutedUser + 1);
      }
      console.log(mutedUser + 2);
  });
  return isMuted;
};

You can't. 你不能。 If you return a string from the function, it will always be passed by value, ie copied; 如果从函数返回一个字符串,它将始终按值传递,即复制; and it's value will not change any more. 它的价值不会再改变了。 You would need to return a function that can access the current value of the local variable, or an object with a property that is changing. 您需要返回一个可以访问局部变量当前值的函数,或者一个具有正在更改的属性的对象。

As you already seem to have an object, option#2 will fit in well here: 由于您似乎已经有了一个对象,因此选项#2适合这里:

function User() { // or whatever you have
    …

    var user = this;
    // If mute button is clicked place them into muted users list
    // check for duplicates in list
    $("#messages-wrapper").on('click', '.message button.muteButton', function(e) {

        $('#unMute').show();

        //store userId in muted user object
        mutedUsers[user.id] = user;
        user.muted = true;
    });
    this.muted = false;
    this.isUserMuted = function() {
        return this.muted ? ' muted' : '';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM