更大更多的用法,將字面字串轉換程式碼的例子,在實物上更深入到資料處理。例如把JSON字串轉換成JSON物件,現在已經有 JSON.parse() ,或是搭配 script 標籤的使用方法,另外還有包裝後變成其他言的形式,轉譯過後再使用 eval 執行編碼過後的JS語言。
var json = '{"name": "Ninja"}';
var object = eval("(" + json + ")");
undefined
object.name
'Ninja'
base2.namespace =
"var Base=base2.Base;var Package=base2.Package;"
console.log(this);
eval(base2.namespace);
console.log(this);
eval(function hello(a){alert("Hello, "+a)}hello("New user");)
describe("Matchers", function() {
it("invokes the provided matcher on a call to expect", function(){
expect(true).to(equal, true);
expect(true).to_not(equal, true);
})
})
<script type="text/javascript">
window.onload = function(){
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++){
if(scripts[i].type == "x/onload"){
globalEval(scripts[i].innerHTML);
}
}
};
</script>
<script type="x/onload">
console.log("Executed on page load.")
</script>
/**
* Constrain.
*
* Move the mouse across the screen to move the circle.
* The program constrains the circle to its box.
*/
float mx;
float my;
float easing = 0.05;
int radius = 24;
int edge = 100;
int inner = edge + radius;
void setup() {
size(640, 360);
noStroke();
ellipseMode(RADIUS);
rectMode(CORNERS);
}
void draw() {
background(51);
if (abs(mouseX - mx) > 0.1) {
mx = mx + (mouseX - mx) * easing;
}
if (abs(mouseY - my) > 0.1) {
my = my + (mouseY- my) * easing;
}
mx = constrain(mx, inner, width - inner);
my = constrain(my, inner, height - inner);
fill(76);
rect(edge, edge, width-edge, height-edge);
fill(255);
ellipse(mx, my, radius, radius);
}
https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520SIMPLE_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250A%252F%252F%2520ADD%2520YOUR%2520CODE%2520HERE%250Afunction%2520hello(name)%2520%257B%250A%2520%2520alert('Hello%252C%2520'%2520%252B%2520name)%253B%250A%257D%250Ahello('New%2520user')%253B%250A%250A
https://processing.org/examples/constrain.html