「ES6」カテゴリーアーカイブ
【JavaScript】Object.crateとassignを使ってnewしないでインスタンスを作る「FactoryFunction」
大変興味深い記事見つけました
ざっくり何をいっているかというと
「あなたがprototypeを理解していないならJavaScriptを理解していない」
衝撃的。。
classの継承はprototypeの継承と同じことですか??スタイルの違いですか??
No
classは青写真、設計図、subクラスとの関係。
いいかえるならclassがないとインスタンスは作れない
インスタンスメソッドはそれ自体class定義されていないと実行できない
まずインスタンスを作ってインスタンス上でメソッドを実行しなくてはならない。
prototype継承は
他のインスタンスから継承しているインスタンス。
prototype委譲して使っている。
インスタンスのprototypeを設定するとオブジェクトへの参照をもつ
オブジェクトは他のオブジェクトへのリンクをもつようになる。(concatenative inheritance 連接継承)
A class is a blueprint.
A prototype is an object instance.
Aren’t classes the right way to create objects in JavaScript?
クラスがオブジェクトを作る正しい方法なの??
No
let animal = {
animalType : "brown",
discribe (){
console.log("fafa")
}
}
これにprototpeに委譲させるObject.createを使って。
let animal = {
animalType : "brown",
discribe (){
console.log("fafa")
}
}
let mouse = Object.assign(Object.create(animal), {animalType: 'mouse'});
mouse.discribe()
//fafa
//mouseに別オブジェクト内のdiscribeメソッドがprototype委譲されている
//animalは「delegate prototype」となる
mose.animalType
//mouse
//自身のpropertyとして持っているのでprototypeチェーンを辿らない
JS Bin on jsbin.com
Object.createは
このまえやりました。
「we could attach delegate prototypes without using constructors and the `new` keyword」
この場合animalをnewとconstructorなしに、prototype委譲できる
「Don’t you need a constructor function to specify object instantiation behavior and handle object initialization?」
細かい初期設定や振る舞いを書くコンストラクターは必要ないってこと??
No
「Any function can create and return objects. When it’s not a constructor function, it’s called a factory function.」
どんな関数も作成、オブジェクトを返せる。それがコンストラクタではないとき、ファクトリー関数といわれる
JS Bin on jsbin.com
記事では
・privacy propertyのもち方
・new keywordが何をしているか
・instance of は嘘つきだ
・newはきもい!
・newを使うときとcreateではパフォーマンスに違いはあるのか
なども解説されています。
面白いし、英語記事から学ぶと英語とコードの勉強になって一石二鳥ですね。
でわまたーーー
【JavaScript】"true"や"false"という文字列をBoolean型に変換、評価する方法
これどうするんだろうって調べていたのですが、日本語記事が見当たらなかったので書きます
【JavaScript】ClassをnewするとかObject.createでインスタンスを作らずprototype継承する外人を見つけた
Why object literals in JavaScript are cool
なるほどなーっと思いましたーー。
でわまたーー。
【React】ブラウザ間の差異をなくすcore.jsをReact内にimportする方法〜ES6,ES7のメソッドを快適に使う〜
以前の記事でObject.assignがios8で使えなくてpolyfillを使った話をしたのですけど、
core-jsで解決できるようなので試してみた。
ES6でimportして実際使ってみるまでの記事です。
読み込む
npm i -D core-js
//React内に読み込む
使いたいオブジェクト名の階層までのパスを書きメソッドを読み込む
import { findIndex, fill } from 'core-js/library/fn/array/virtual'; import { includes }from 'core-js/library/fn/array/'; import { assign } from 'core-js/library/fn/object'; const HelloReact = React.createClass({ render() { console.log(Array(10)::fill(0).map((a, b) => b * b)::findIndex(it => it && !(it % 8))); var obj = {a: "fa"}; console.log(assign({b: 'ooo'}, obj)); var array = ["","faf"] console.log(array.includes("faf")); return ( <div> <div>
////
【ES6】適当に試したり。正規表現とか
[code lang="javascript"]
function getKey(k) {
return `${k}`;
}
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
console.log(obj)
///////////////////////////
function f(x, ...y) {//ここで受け取らない分が配列の要素としてyになる
// y is an Array
console.log(y)//["hello","true"]
return x * y.length;
}
const r1 = f(3, "hello", true) == 6
console.log(r1);//true
//////////////////////////////
function f(x, y, z, t, p) {//インデックス順に受け取る
console.log(z);
return x + y + z;
}
// Pass each elem of array as argument
//const arry = [1,2,3,5,6];
//f(...arry) == 6
//or
f(...[1,2,4]);
///////////////////////////////
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
console.log([pre, cur] = [cur, pre + cur]);
return { done: false, value: cur }
}
}
}
}
//////////////////////
let [a, b, c] = []
console.log(a,b,c);
typeof b
function getSomething(){
return {
first: 1,
second: 2,
third: 3
}
}
var { first, second, third } = getSomething();
console.log(first)
console.log("repeat".repeat(2));
console.log(["morita","kenji","fafafa"].findIndex(x => x == "fafafa"))
console.log(["A","B","C"].map(x => Array.of(x)));
console.log(['a', 'b', 'c'].fill('kenji', 1, 2));
const i = [3, 0, 6, -1].find(x=> x < 0);
console.log(i)
function* idMaker(){
var index = 0;
while(true)
yield index++;
}
const gen = idMaker();
console.log(gen)
////////////////////////////
const str = "わたしの名前は「もりた」です。あだなは「もりけん」です";
const re = /「.*?」/ig;
const myRe=/ken*/g;
const str2 = "fafakenfafkenji";
let array;
while ((array = myRe.exec(str2)) !== null) {
let msg = array[0] + " を見つけました。";
msg += "次のマッチは " + myRe.lastIndex + " からです。";
console.log(msg);
}
const str3 = "<img src='fafa.com'>"
const str4 = "<p>"
const reg2 = /<(\S+)(\s+.+)?>/;
const reg3 = /<(?:\S+)(?:\s+.+)?>/;
const re2 = str3.match(reg2);
const re3 = str3.match(reg3);
const re4 = str4.match(reg2);
console.log(re2);console.log(re2[0]);
console.log(re3);console.log(re3[0]);
console.log(re4);console.log(re4[0]);
const str222 = "わたしの名前は「もりた」です。あだなは「もりけん」です";
const re222 = /「(.+?)」/ig;
let result;
while ((result = re222.exec(str222)) !== null){
console.log(result[0],"ここ")
}
const nen = "西暦1980年の3581歳です";
const reg1 = /\d+(?=年)/;
console.log(nen.match(reg1))
const string3 = "washable reasonable accessible assemble answerable";
const reg5 = /\b\w+(?=able\b)/g;
console.log(string3.match(reg5));
const nen1 = "ケンジは昭和55年生まれの35歳であり、ケンジの母は昭和22年生まれの64歳である"
const reg6 = /\d+(?![年\d])/g;
console.log(nen1.match(reg6));
const str5 = "あの客はよく柿食う客だ";
const res5 =str5.match(/あの(.+)はよく柿食う\1だ/);
console.log(res5);
const tag = "<div><h1>kenjimorita.jp</h1></div>";
console.log(/<(\w+)><(\w+)>kenjimorita.jp<\/\2><\/\1>/.test(tag))
// const str6 = "西暦2010年は平成22年です。西暦1980年は昭和55年です。";
// console.log(str6.match(/(?<=昭和|平成)\d+/))
const str7 = "My name is Taro Suzuki and I am a researcher at ABC.";
console.log(str7.match(/\ba\w*\b/g));
var falseValue = new Boolean(false);
console.log(falseValue)//false
var fafa = null;
console.log(typeof fafa)//Object
console.log(fafa == undefined)//等値演算子ではtrueになってしまう
console.log(fafa === null);//true //同値演算子を使う
[/code]
Chrome CanaryのconsoleでECMAScript2015試せるよ
【ECMAScript2015(ES6)】後で猫に教えてあげたいES6の「Generators(ジェネレーター)とIterator(イテレータ)」
昨日はSymbol(シンボル)でしたが、今日はGeneratorsとIterator。
babel立ち上げてコード確認しながらやりました。
ジェネレータってなにかって再帰処理を簡単にしてくれるものなんですね。
そのイテレータオブジェクトを返す関数がジェネレータ
ジェネレータを扱うにはイテレータを理解する必要があるようです。
続きを読む
ES6 static menber
【ECMAScript2015(ES6)】後で猫に教えてあげたいES6の「Symbol(シンボル)」
【React】babelでbabel-preset-stage-0や使う方法「ES7 Property Initialiazers for Default Props and Prop 」を使いたい方へ
英語文しかなかったので自分のようなReactにおいて「ES7 Property Initialiazers for Default Props and Prop」を使いたい方へ記事書きました
参照 https://babeljs.io/blog/2015/10/29/6.0.0 https://egorsmirnov.me/2015/06/14/react-and-es6-part2.html
babelは6系からそれぞれプラグインをインストールすることになったみたいです。
具体的には これらを適当にインストールしてください(適当です)
"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-plugin-syntax-class-properties": "^6.5.0",
"babel-plugin-transform-class-properties": "^6.6.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"babelify": "^6.1.3",
その後 package.jsonに下のようにpresetsを設定(使いたいpresetのプラグインです)上のならbebel-plugin-[ここ] 「ES7 Property Initialiazers for Default Props and Prop 」はstage-0として設定すればOK .babelrcだったらpackage.jsonと同じ階層に置けばいいみたいです。今回はjsonに記述します。
"babel": {
"presets" : ["es2015", "react", "stage-0"
]
},
"devDependencies": {
//some
}
で gulpfileのtransformのところに
.transform("babelify", {presets: ["es2015", "react", "stage-0"]})
でok
ちょっとエラーが出たり分からなかった場合下記リンク先に playgroundあげてありますので余計なソースを削って使ってください。 ミニマムでReact,ES6の最新が動作できるようにされています。
https://github.com/kenmori/React-ES6-Flux-Playground/tree/master/playground
【 併せて読みたい 】
【REACT】REACTの動きを理解したい人の為の最小サンプル
【REACT入門】過去のREACT初心者の自分にREACTのPROPSとSTATEの違いを簡単に説明してあげたい
【REACT × ES6 × FLUX】を手っ取り早く学びたい人の為にサンプル作ったよ【3の倍数と3が付くときだけ猫になるCOUNTER】
Tagged template strings(タグテンプレートストリング)
Tagged template strings(タグテンプレートストリング)が多分便利なので 理解したことを書いておく コードはコチラ
もしも下記のように呼び出した場合、
[code language="javascript"] tag'もりた${kenji}です' [/code]
ES5でいうこのようなものとして呼び出している tag(["もりた","です"], kenji)
tagの第一引数に["もりた","です"]という変数として展開されない文字列が要素となる配列を受け取る それ以外のkenjiは第二引数以降受け取れる。 上記が
tag'もりた${kenji}です${yeah}' だとした場合 引数の数が増える
下記のように受け取った第一引数の配列のインデックスを参照することも可能(もちろん)
function tag(strings, ...values){ console.log(strings[0]) //もりた console.log(strings1) //です }
具体的な使用例
var long = '30px'; var weight = '40px';
function tag(strings, ...values){ return m:${values[0]}、p:${values[1]}
; };
var str1 = tag身長${long}で、体重は${weight}です
;
console.log(str1);