简体   繁体   English

如何在没有状态变量的情况下更新函数表达式?

[英]How to update my function expression without state variables?

I'm creating a game in jquery and the player is created on click of a button. 我在jquery中创建一个游戏,并且单击按钮即可创建播放器。 This is my function expression I use to hold it's info: 这是我用来保存其信息的函数表达式:

var getPlayerData = function() {
    return {
        name: $("#name").val(),//get name from input
        office_name: $("#office-name").val(), //get name from input
        score: parseInt($('#score').text(), 10), //players startwith 1k HC
        office_location: "office_loc1", //set Player's office
        office_multiplier: office_loc1, // Set Players office multiplier
        notified: false,
        projects_completed: 0
    };
};

Then I run this function within my other functions to access the player's variables, like so: 然后,在其他函数中运行此函数以访问播放器的变量,如下所示:

$('#create-player').click(function startProject() {
    getPlayerData();
});

I need a way to update both the office_location and office_multiplier variables using a conditional. 我需要一种使用条件更新office_locationoffice_multiplier变量的方法。 The office multipliers are referencing this set of variables: 办公室乘数引用这组变量:

var office_loc1 = .01,
    office_loc2 = .02,
    office_loc3 = .03,
    office_loc4 = .04,
    office_loc5 = .05,

This is the conditional that I am trying to update some of those functions, here are the steps to the if conditional: 这是我尝试更新其中一些功能的条件,以下是if条件的步骤:

  1. get score from html, check it it's > 0 && 从html获取分数,检查它是否为> 0 &&
  2. Check multipler is = office_loc1 variable && 检查倍数是= office_loc1变量&&
  3. check if the player_notified = false 检查player_notified = false

if (parseInt($('#score').text(), 10) > 0 && getPlayerData().office_multiplier === office_loc1 && getPlayerData().notified === false){ }

The key parts to pay attention to in the conditional are: 条件中要注意的关键部分是:

//upgrade players office and notify them
      getPlayerData().office_location = "office_loc2";
      getPlayerData().office_multiplier = office_loc2;
      getPlayerData().notified = true;

However, this will not actually update the variable. 但是,这实际上不会更新变量。 Does anyone have any ideas on this? 有人对此有任何想法吗?

Thanks! 谢谢!

You are creating a new object instance of the player each time you call getPlayerData 每次调用getPlayerData时,您都在创建播放器的新对象实例。

If it is a read-only object, that wouldn't be a problem, but once you try to mutate any property of it, you will loose the updated value once you call getPlayerData() again. 如果它是一个只读对象,那将不成问题,但是一旦您尝试对该对象的任何属性进行突变,则再次调用getPlayerData()后,您将失去更新后的值。

You should keep the playerData as an instance variable, then you can access through your code. 您应该将playerData保留为实例变量,然后才能通过代码进行访问。

var playerData = getPlayerData();

------------- edit ------------- -------------编辑-------------

Right after defining the getPlayerData function, you create a var playerData. 在定义getPlayerData函数之后,立即创建一个var playerData。 Like this: 像这样:

var getPlayerData = function() {
    return {
        name: $("#name").val(),//get name from input
        office_name: $("#office-name").val(), //get name from input
        score: parseInt($('#score').text(), 10), //players startwith 1k HC
        office_location: "office_loc1", //set Player's office
        office_multiplier: office_loc1, // Set Players office multiplier
        notified: false,
        projects_completed: 0
    };
};
var playerData = getPlayerData();

Then, on everyplace you would call getPlayerData() , you use playerData instead. 然后,在每个地方都将调用getPlayerData() ,而是使用playerData

Part I 第一部分

This code: 这段代码:

$('#create-player').click(function startProject() {
    getPlayerData();
});

is a bit suspicious. 有点可疑。 As per Flanagan, function can be invoked and it may not return any value, but if it does, then supposing that you want to store invocation result somewhere, just assign function invocation result to a variable. 根据Flanagan,函数可以被调用,并且可能不返回任何值,但是如果这样做,则假定您要将调用结果存储在某个地方,只需将函数调用结果分配给变量。

var someVar = getPlayerData();

Otherwise the following happens: 否则会发生以下情况:

  • You invoke getPlayerData function 您调用getPlayerData函数
  • The function returns an object 该函数返回一个对象
  • The object is evaluated 对象被评估
  • Because assignment operator is missing, the object is discarded 由于缺少赋值运算符,因此将对象丢弃

As if js would say: "I've executed the function, I see an object, but I don't see what I should do with it... let me just leave it as it is" 好像js会说:“我已经执行了函数,我看到了一个对象,但是我看不到该怎么做……让我照原样保留它”

Part II. 第二部分 What would I suggest.. 我有什么建议。

If you want to create an object, there's another way. 如果要创建对象,则有另一种方法。 At first glance I treated the following code as an object consructor: 乍一看,我将以下代码视为对象构造器:

var getPlayerData = function() {
    return {
        name: $("#name").val(),//get name from input
        office_name: $("#office-name").val(), //get name from input
        score: parseInt($('#score').text(), 10), //players startwith 1k HC
        office_location: "office_loc1", //set Player's office
        office_multiplier: office_loc1, // Set Players office multiplier
        notified: false,
        projects_completed: 0
    };
};

Instead of this, you could create an object with some functions that would update the fields you want to be updated. 取而代之的是,您可以创建具有某些功能的对象,这些功能将更新您要更新的字段。 Let me demonstrate.. 让我示范一下

var PLAYER_DATA = function(name, office_name, score, office_location, office_multiplier, notified, projects_completed) {
    var nname = name,
        ooffice_name = office_name,
        sscore = parseInt(score, 10),
        ooffice_location = office_location,
        ooffice_multiplier = office_multiplier,
        nnotified = notified,
        pprojects_completed = projects_completed;

    function setName (name) {
        nname = name;
    }

    function getName() {
        return nname;
    }

    function setOfficeName(officeName) {
        ooffice_name = officeName;
    }

    function getOfficeName() {
        return ooffice_name;
    }

    function setScore(score) {
        sscore = parseInt(score, 10);
    }

    function getScore() {
        return sscore;
    }

    function setOfficeLocation(officeLocation) {
        ooffice_location = officeLocation;
    }

    function getOfficeLocation() {
        return ooffice_location;
    }

    function setOfficeMultiplier(officeMultiplier) {
        ooffice_multiplier = officeMultiplier;
    }

    function getOfficeMultiplier() {
        return ooffice_multiplier;
    }

    function setNotified(notified) {
        nnotified = notified;
    }

    function isNotified() {
        return nnotified;
    }

    function setProjectsCompleted(amount) {
        // is zero by default
        pprojects_completed = (amount > 0) ? amount : 0;
    }

    function getProjectsCompleted() {
        return pprojects_completed;
    }




    return {
        setName: setName,
        getName: getName,
        setOfficeName: setOfficeName,
        getOfficeName: getOfficeName,
        setScore: setScore,
        getScore: getScore,
        setOfficeLocation: setOfficeLocation,
        getOfficeLocation: getOfficeLocation,
        setOfficeMultiplier: setOfficeMultiplier,
        getOfficeMultiplier: getOfficeMultiplier,
        setNotified: setNotified,
        isNotified: isNotified,
        setProjectsCompleted: setProjectsCompleted,
        getProjectsCompleted: getProjectsCompleted
    }
};

After that you need to create this object passing some initial values as arguments to the conscructor: 之后,您需要创建此对象,并将一些初始值作为参数传递给构造器:

var somePlayerData = new PLAYER_DATA($("#name").val(),
                                     $("#office-name").val(),
                                     // Notice that parseInt will be executed while creation of PLAYER_DATA 
                                     // object so there's no need to parse it again
                                     $('#score').text(),
                                     "office_loc1",
                                     "office_loc1",
                                     false,
                                     0)

After that you can access object's values via getters and set some values you want via setters 之后,您可以通过getter访问对象的值,并通过setter设置一些所需的值

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

相关问题 如何在 React 中更新我的 state 数组而不更新 function - How do I update my state array without having update function in React 如何在没有回调函数的情况下使用 react Hook 状态变量? - How to use react Hook state variables without a callback function? 如何在函数中调用“setState”作为回调,没有任何新的状态值,成功更新状态? - How does calling "setState" as a callback in a function, without any new state value, successfully update the state? 如何根据我的初始 state 更新 state - How to update the state based on my initial state 错误:setState(...):需要一个状态变量对象来更新或一个返回状态变量对象的函数 - Error: setState(...): takes an object of state variables to update or a function which returns an object of state variables 如何在函数执行期间比较状态变量? - How to compare state variables during function execution? 如何更新状态而不将其传递给子组件 - How to update state without passing it to child component 如何在不刷新reactjs页面的情况下更新状态 - How to update state without refreshing page in reactjs 如何通过在无状态组件中的开关内调用函数来更新父状态? - How can I update the parent state by calling a function within a switch in my stateless component ? React:如何从外部函数更新组件状态? - React: How do I update my components state from an external function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM