Created
November 11, 2010 14:22
-
-
Save azu/672549 to your computer and use it in GitHub Desktop.
new演算子の動作
This file contains 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
// http://nanto.asablo.jp/blog/2005/10/24/118564 の 擬似的なnew演算子の動作 | |
F.applyNew([param1, param2]); // == new F(param1, param2) をやったとき | |
// => this : F , args : [param1, param2] | |
Function.prototype.applyNew = function (args) { | |
var that = this;// 解説的にややこしいのでthatにする | |
var Constructor = function () {};//空のオブジェクト作る | |
Constructor.prototype = this.prototype;// prototypeの設定をする | |
var instance = new Constructor();// instanceを作る | |
var result = that.apply(instance, args); | |
// instanceをthisに設定してF(that)を呼び出す(引数は new F(args) で書いたargsの部分) | |
return (result instanceof Object) ? result : instance; | |
// Fを呼び出した結果 オブジェクトが返ってきたならそのままそれをreturnする。 | |
// オブジェクト以外(何も返さない時など)の場合、instanceを返す。 | |
// Fのコンストラクタ関数内でthis.x = "nantoka" とかあったら、instanceはいろいろ拡張されてる。 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment