JavaScript

JS パーツ1

More than 1 year has passed since last update.


webmodules

ES6 modules for web usage – on NPM

https://github.com/webmodules


You-Dont-Need-jQuery

https://github.com/oneuijs/You-Dont-Need-jQuery/blob/master/README-ja.md


closure


good.js


//クロージャー

function createCounter(){
var count = 0;
return function(){
count++;
console.log(count);
}
}

var counter1 = createCounter();
counter1(); //1
counter1(); //2
counter1(); //3

var counter2 = createCounter();
counter2(); //1
counter2(); //2

count = 100; //エラー



good.js


//クロージャー

var module = (function() {
var count = 0;

return {
increment: function() {
count++;
},
show: function() {
console.log(count);
}
};

})();

module.show(); // 0
module.increment();
module.show(); // 1



prototype


bad.js


//インスタンスの数だけメモリ確保はよくない

function Human(name){
this.name = name;
this.greet = function(){
console.log("My name is " + this.name);
};
}

var alice = new Human("Alice");
alice.greet(); //My name is Alice

var bob = new Human("Bob");
bob.greet(); //My name is Bob



good.js


//prototype使う

function Human(name){
this.name = name;
}
Human.prototype.greet = function(){
console.log("My name is" + this.name);
};
var alice = new Human("Alice");
alice.greet();

var bob = new Human("Bob");
bob.greet();