javascript how to create reference

后端 未结 5 1721
孤独总比滥情好
孤独总比滥情好 2021-01-05 20:45

Could you propose any workarounds to implement a reference to variable using closures or any other tricks?

createReference = function() {
    // TODO: how to         


        
5条回答
  •  Happy的楠姐
    2021-01-05 21:26

    You have to use a string of the variable name but I think this is as close as you'll ever get in JavaScript:

    var createReference = function (context, prop) {
      return function () { return context[prop]; };
    };
    
    var x = 5;
    var refX = createReference(this, 'x');
    x = 6;
    
    alert(refX()); // alerts 6
    

    Edit:

    In your updated scenario it would be better to use a closure directly, so that you don't have to use a string of the variable name:

    var createReference = function (context, func) {
        return function () { return func.call(context); }
    };
    
    Provider = function() {
    };
    Provider.prototype.x = 5;
    Provider.prototype.getXRef = function() {
    
        return createReference(this, function () { return this.x; });
    
        // OR if you happen to be running in a 
        // JavaScript 1.8 environment like Firefox 3+,
        // you can use "expression closures" for more
        // concise code:
    
        // return createReference(this, function () this.x);
    };
    Provider.prototype.incrementX = function() {
        this.x = this.x + 1;
    };
    
    var provider = new Provider();
    var refX = provider.getXRef();
    provider.incrementX();
    alert(refX()); // alerts 6
    

提交回复
热议问题