【问题标题】:Send value from a method to another in jquery在jquery中将值从一个方法发送到另一个方法
【发布时间】:2015-07-27 07:42:01
【问题描述】:

我有以下代码:

pz.flashCall = {
    updateChest: function (value, type) { 
        console.log(result);    
    },
    gameResult : function (result, level){
        var result = result;
    }

问题是如何将变量result 从方法gameResult() 发送到updateChest(),我尝试使用var 但没有结果。你能帮我吗 ? 提前谢谢

【问题讨论】:

  • 你试过window.result吗?

标签: javascript jquery jquery-ui javascript-events


【解决方案1】:

有几种方法可以做到这一点。这是最简单和最糟糕的方法:全局变量。

// res is available globally
var res;

pz.flashCall = {
    updateChest: function (value, type) { 
       // Access global variable `res`
       console.log(res);    
    }
    ,gameResult : function (result, level){
        // Set the global variable `res`
        res = result;
    }
...

另一种方法是将变量存储在flashCall 对象上。这假设您将始终调用来自flashCall 的方法,即flashCall.gameResult()flashCall.updateChest()

pz.flashCall = {
    updateChest: function (value, type) {
       // Access `flashCall.result`
       console.log(this.result);    
    }
    ,gameResult : function (result, level){
        // Set `flashCall.result`
        this.result = result;
    }
...

【讨论】:

    【解决方案2】:

    // 结果 - 现在是一个全局变量。您可以从任何地方拨打电话

    var result;
    var  flashCall = {
        updateChest : function(p_value,p_type){
           console.log(result); 
       },
        gameResult : function(p_result,p_level){
           result = p_result;
        }
    }
    

    // 或像下面这样在类中声明并像 //flashCall.result 一样从外部调用它

    var flashCall = {
        result:null,
        updateChest : function(p_value,p_type){
           console.log(this.result); 
        },
        gameResult : function(p_result,p_level){
            this.result = p_result;
        }
     }
    

    这样你可以全局声明变量

    【讨论】:

    • 这个答案将大大受益于正确的代码格式和一些解释。
    • 谢谢乔恩。会改进我的答案
    猜你喜欢
    • 2023-04-09
    • 2019-03-02
    • 2022-08-14
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多