如何获得另一个功能的所有者功能

时间:2016-09-02 09:07:56

标签: javascript jquery

关于jsfiddle的示例:https://github.com/pleerock/class-transformer

MyEnum["someServerString"]

我希望实现的目标是点击相应的(function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the code... } $('.container').on('click', 'button', function(){ getVar(this.dataset.target); }) }(jQuery)) 后获取foo_valuebar_value

我知道,我只能通过检查button来做到这一点,但我试图找到一种方法来获取IIFE函数的范围(包含其余代码)并从中获取变量foo和bar它。 当我做if(theVar==foo)(我认为它将指出拥有函数),但我得到console.log(this)对象。我也试图进入这个变量dom窗口范围,但没有任何工作正常。 这样做有选择吗?

2 个答案:

答案 0 :(得分:1)

  

我想得到变量,它被命名为函数getVar

的theVar参数

在这种情况下,将变量声明为对象的属性会更容易。然后,您可以使用括号表示法通过变量访问这些属性。试试这个:

var vars = {
  foo: 'foo_value',
  bar: 'bar_value'
}

function getVar(theVar) {
  console.log(vars[theVar]);
}

getVar('foo');
getVar('bar');

答案 1 :(得分:0)

你能试试这个here

吗?
function getVar(theVar){
  console.log(this[foo]);
  console.log(this[bar]);
  //the code...
}       

可以替换为

function getVar(theVar){
 console.log(foo);
 console.log(bar);
 //the code...
}       

this[foo]会返回undefined

  1. this这里是内部函数的上下文,即getVar
  2. 即使this是外部上下文,外部函数也没有名称为foo的对象键。相反,它有变量。如果实际上你想使用这种方法,试试这个:

    (函数($){     this.foo ='foo_value';     this.bar ='bar_value';     var self = this;     function getVar(theVar){       的console.log(个体[富]);       的console.log(个体[巴]);       //代码...     }

    this.foo_value = "some random string";
    this.bar_value = "some other string";
    
    $('.container').on('click', 'button', function(){
        getVar(this.dataset.target);
    })}(jQuery))
    
  3. 请参阅此处的工作示例

     (function($){
            this.foo = 'foo_value';
            this.bar = 'bar_value';
            var self = this;
            function getVar(theVar){
              console.log(self[foo]);
              console.log(self[bar]);
              //the code...
            }       
    
            this.foo_value = "some random string";
            this.bar_value = "some random string";
       
            $('.container').on('click', 'button', function(){
                getVar(this.dataset.target);
            })
        }(jQuery))
    <div class="container">
    	<button data-target='foo'>foo</button>
    	<button data-target='bar'>bar</button>
    </div>

相关问题