Skip to content

Instantly share code, notes, and snippets.

@monjudoh
Created September 11, 2012 05:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monjudoh/3696129 to your computer and use it in GitHub Desktop.
Save monjudoh/3696129 to your computer and use it in GitHub Desktop.
classboxよく分かってないんだけどJavaScriptでやるとこんな感じ?__proto__のsetを使っているので標準準拠で実装できません。
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"
}
@monjudoh
Copy link
Author

classbox関数に渡したcallback関数の中で第一引数のpatch関数にarrayを渡すと、そのcallback関数の実行中だけprototypeを差し替えるというシロモノ。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment