Created
September 11, 2012 05:18
-
-
Save monjudoh/3696129 to your computer and use it in GitHub Desktop.
classboxよく分かってないんだけどJavaScriptでやるとこんな感じ?__proto__のsetを使っているので標準準拠で実装できません。
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
var classbox = (function () { | |
var proto = Array.prototype; | |
var proto2 = Object.create(Object.getPrototypeOf(proto)); | |
Object.getOwnPropertyNames(proto).forEach(function(propName){ | |
var desc = Object.getOwnPropertyDescriptor(proto,propName); | |
Object.defineProperty(proto2,propName,desc); | |
}); | |
proto2.first = function first() { | |
return this[0]; | |
}; | |
Object.getOwnPropertyNames(proto2).forEach(function(propName){ | |
var desc = Object.getOwnPropertyDescriptor(proto2,propName); | |
if (!desc.enumerable) { | |
desc.enumerable = false; | |
Object.defineProperty(proto2,propName,desc); | |
} | |
}); | |
var pachedObjects = []; | |
function patch(object){ | |
object.__proto__ = proto2; | |
pachedObjects.push(object); | |
} | |
return function (callback) { | |
try { | |
callback(patch); | |
} catch (e) { | |
} finally { | |
pachedObjects.forEach(function(object){ | |
object.__proto__ = proto; | |
}); | |
pachedObjects = []; | |
} | |
} | |
})(); | |
var arr = [1,2]; | |
try { | |
arr.first(); | |
} catch (e) { | |
console.error(e); // "undefined_method" | |
} | |
classbox(function(patch){ | |
patch(arr); | |
console.log(arr.first()); // 1 | |
}); | |
try { | |
arr.first(); | |
} catch (e) { | |
console.error(e); // "undefined_method" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
classbox関数に渡したcallback関数の中で第一引数のpatch関数にarrayを渡すと、そのcallback関数の実行中だけprototypeを差し替えるというシロモノ。