-
-
Save RangerMauve/7839994 to your computer and use it in GitHub Desktop.
This is a neat idea I had for having variables that act like primitive values but are actually functions. Useful for having complex variables that automagically update.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This calls the function whenever a primitive is needed | |
function R(fn){ | |
return { | |
valueOf:fn, | |
toString:function(){ | |
return fn()+""; | |
} | |
}; | |
} | |
var t = 0; | |
var x = R(function(){ | |
return Math.sin(t); | |
}); | |
// You can combine them by using R each time | |
var y = R(function(){ | |
return x / 2; | |
}); | |
log(x) // 0 | |
// Changes in t affect x right away | |
t = Math.PI/2; | |
log(x); // 1 | |
// Works as expected and calls x/2 | |
log(y); // 0.5 | |
// Values are passed by reference | |
var z = y; | |
log(z); // 0.5 | |
t = 0; | |
log(z); // 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo JS fiddle: http://jsfiddle.net/R5SBK/2/