Created
November 9, 2011 10:39
-
-
Save 0mg/1351079 to your computer and use it in GitHub Desktop.
JS記
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f(){return f} | |
この関数 f を呼ぶと、関数 f を返す。 // f() is f | |
返ってきた関数 f を呼ぶと、やはり関数 f を返す。 // f()() is f | |
f()()()()()()() も f である。 | |
f()()()()()()()()()()()() も f である。 | |
--- | |
function O(x) { | |
this.x = x; | |
} | |
new O(3); | |
これは正しいコンストラクタの使い方だ。 | |
O(3); | |
これは間違っている。 new をつけずに呼ぶと、 O はコンストラクタではなく、ただの関数として実行される。 | |
すなわち this は window となり、 window.x への代入をしてしまうことになる。 | |
開発者が賢明ならば、new をつけないで呼び出すことなどないから問題ない。 | |
つけ忘れた場合でも、どこかでエラーが出るはずだ。つければよい。 | |
new を必ずつけてほしい場合は、 new をつけないで呼び出すとエラーになるように書けばよい。 | |
function O(x) { | |
if (!(this instanceof arguments.callee)) throw Error("new をつけろよデコ助野郎!"); | |
this.x = x; | |
} | |
--- | |
Object.prototype.x = null; | |
for(i in {}); | |
i に "x" が入る。 | |
for(i in {a:1,b:2}); | |
i に "a", "b", "x" が入る。 | |
この時、 i に入ってほしいのは "a", "b" だけだ。 | |
なぜなら、 for in とは、 | |
for(i=0; i<a.length; ++i); | |
[配列の][インデックス]をすべてなめる | |
と同じように、 | |
{オブジェクトの}["プロパティ名"]をすべてなめる | |
のために存在するからであり、 | |
そのような動作であると期待して使用するのが人間だからだ。 | |
Object.prototype 以外ならば、どんな prototype でも自由に変更してよい。 | |
Array.prototype, | |
String.prototype, | |
Number.prototype, | |
RegExp.prototype, | |
Boolean.prototype., | |
{object} 以外のオブジェクトには for in を使うことがない。 | |
[array] に使うことは許されない。 | |
[array] には for を使おう。絶対に for in を使ってはならない。 | |
なぜならば、 for in は {object} をなめるために在る文だからである。 | |
for(i in x); の x に [array] を入れても機能するからといって、 | |
使用許可が下りているわけではない。 | |
for in は {object} のためだけに存在しているのだ。 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment