iT邦幫忙

2022 iThome 鐵人賽

DAY 19
0
Modern Web

JS 忍者訓練計畫系列 第 19

忍者煉金術:執行期間程式計值(下) Day18

  • 分享至 

  • xImage
  •  

更大更多的用法,將字面字串轉換程式碼的例子,在實物上更深入到資料處理。例如把JSON字串轉換成JSON物件,現在已經有 JSON.parse() ,或是搭配 script 標籤的使用方法,另外還有包裝後變成其他言的形式,轉譯過後再使用 eval 執行編碼過後的JS語言。

這章想學到什麼?

  • 轉換 JSON
  • 匯入有命名空間的程式
  • JavaScript 程式碼的壓縮與混淆
  • 動態程式碼改寫
  • 剖面導向腳本程式標籤
  • 後設語言和DSL

程式碼閱讀練習與撰寫

轉換 JSON

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);

JavaScript 程式碼的壓縮與混淆

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>

後設語言和DSL

/**
 * 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


上一篇
忍者煉金術:執行期間程式計值(上) Day17
下一篇
with 述句(上) Day19
系列文
JS 忍者訓練計畫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言