在 jQuery 中将值从一个方法发送到另一个方法

Send value from a method to another in jQuery

我有以下代码:

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

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

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

// 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;
    }
...

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

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

// 或像下面这样在 class 内部声明并从外部调用它 //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;
    }
 }

像这样你可以全局声明变量