一、迴圈與迭代 Iteration
倘若使用手動迭代的方式,比如`(for i=0, i<9, i++)`,那麼程式設計就會陷入到dirty-details之中。
ES6標準化了specifi-protocol的iterator-pattern.
// an array is an iterable var arr = [ 10, 20, 30 ]; for (let val of arr) { console.log(`Array value: ${ val }`); } //map and destruction var buttonNames = new Map(); buttonNames.set(btn1,"Button 1"); buttonNames.set(btn2,"Button 2"); for (let [btn,btnName] of buttonNames) { btn.addEventListener("click",function onClick(){ console.log(`Clicked ${ btnName }`); }); } // values, keys and entries for (let btnName of buttonNames.values()) { console.log(btnName); } // Button 1 // Button 2
二、閉包 Closure Closure的定義:
Closure is when a function remembers and continues to access variables from outside its scope, even when the function is executed in a different scope.
示例應用:
function counter(step = 1) { var count = 0; return function increaseCount(){ count = count + step; return count; }; } var incBy1 = counter(1); var incBy3 = counter(3); incBy1(); // 1 incBy1(); // 2 incBy3(); // 3 incBy3(); // 6 incByf3(); // 9
在event中的應用:
for (let [idx,btn] of buttons.entries()) { btn.addEventListener("click",function onClick(){ console.log(`Clicked on button (${ idx })!`); }); }
三、this關鍵詞的functionFunction內的this關鍵詞要看其execution-context,首先定義 this-aware的function。
function classroom(teacher) { return function study() { console.log( `${ teacher } says to study ${ this.topic }` ); }; } var assignment = classroom("gaowei");
然後將其分派到object中:
var homework = { topic: "JS", assignment: assignment }; homework.assignment(); // gaowei says to study JS
另外一種調取方法:
var otherHomework = { topic: "Math" }; assignment.call(otherHomework); // Kyle says to study Math
四、Prototype定義homework,雖有隻有topic這一個property,但卻linkage-connect到Object.prototype的多個屬性。
> let homework = {... topic: "JS",... }undefined> homework.homework.__defineGetter__ homework.__defineSetter__homework.__lookupGetter__ homework.__lookupSetter__homework.__proto__ homework.constructorhomework.hasOwnProperty homework.isPrototypeOfhomework.propertyIsEnumerable homework.toLocaleStringhomework.toString homework.valueOfhomework.topic
五、Object Linkage
檢視下面的案例:
var homework = { topic: "JS" }; var otherHomework = Object.create(homework); otherHomework.topic; // "JS" homework.topic; // "JS" otherHomework.topic; // "JS" otherHomework.topic = "Math"; otherHomewokrk.topic; // "Math" homework.topic; // "JS" -- not "Math"
最新評論