倘若使用手动迭代的方式,比如`(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 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 })!`);
});
}
Function内的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
定义homework,虽有只有topic这一个property,但却linkage-connect到Object.prototype的多个属性。
> let homework = {
... topic: "JS",
... }
undefined
> homework.
homework.__defineGetter__ homework.__defineSetter__
homework.__lookupGetter__ homework.__lookupSetter__
homework.__proto__ homework.constructor
homework.hasOwnProperty homework.isPrototypeOf
homework.propertyIsEnumerable homework.toLocaleString
homework.toString homework.valueOf
homework.topic
查看下面的案例:
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"
页面更新:2024-06-17
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号