2012-02-01 91 views
6

在我尝试做这样鲁莽的事情之前,让我告诉你,我不会在现实生活中这样做,这是一个学术问题。从错误中恢复

假设我正在编写一个库,我希望我的对象能够根据需要组合方法。

例如,如果你想叫一个.slice()方法,我没有一个那么window.onerror处理程序将启动它,我

反正我这个​​

window.onerror = function(e) { 
    var method = /'(.*)'$/.exec(e)[1]; 
    console.log(method); // slice 
    return Array.prototype[method].call(this, arguments); // not even almost gonna work 
}; 

var myLib = function(a, b, c) { 
    if (this == window) return new myLib(a, b, c); 
    this[1] = a; this[2] = b; this[3] = c; 
    return this; 
}; 

var obj = myLib(1,2,3); 

console.log(obj.slice(1)); 

也发挥各地(也许我应该开始一个新的问题),我可以改变我的构造函数采取未指定数量的参数?

var myLib = function(a, b, c) { 
    if (this == window) return new myLib.apply(/* what goes here? */, arguments); 
    this[1] = a; this[2] = b; this[3] = c; 
    return this; 
}; 

顺便说一句,我知道我可以载入我的对象与

['slice', 'push', '...'].forEach(function() { myLib.prototype[this] = [][this]; }); 

这不是我要找的

+0

这听起来像你想关于JavaScript [ “pollyfills” 或 “垫片”(http://remysharp.com/2010/10/08/what-is-a-polyfill/) – 2012-02-01 19:54:59

+1

捎带使用try-catch块捕获异常通常更优雅和可靠。 – 2012-02-01 19:57:32

回答

4

至于你问的是一个学术问题,我想浏览器的兼容性不是问题。如果确实不是这样,我想介绍一下和谐代理。 onerror不是一个很好的做法,因为它只是一个事件如果某处发生错误。它应该,如果有的话,只能用作最后的手段。 (我知道你说你不使用它,但onerror是不是很开发友好。)

基本上,代理使您能够拦截JavaScript中的大多数基本操作 - 最显着的是获取任何属性这里很有用。在这种情况下,你可以拦截获得.slice的过程。

请注意,默认情况下,代理是“黑洞”。它们不对应任何对象(例如,在代理上设置属性只需调用set陷阱(拦截器);实际存储你必须自己做)。但有一个“转发处理程序”可用于将所有内容都路由到一个普通对象(或课程的一个实例),以便代理的行为与普通对象相同。通过扩展处理程序(在这种情况下,get部分),您可以非常容易地通过如下方式路由Array.prototype方法。

所以,每当任何属性(名称为name)被获取,代码路径如下:

  1. ,请返回inst[name]
  2. 否则,请尝试返回一个函数,该函数对具有此函数的给定参数的实例应用Array.prototype[name]
  3. 否则,只需返回undefined

如果你要玩的代理,你可以在Chromium的每晚构建使用最新版本V8,例如(确保为chrome --js-flags="--harmony"运行)。同样,代理不适用于“正常”用法,因为它们相对较新,改变了JavaScript的许多基本部分,实际上还没有正式指定(仍然是草稿)。

这是怎么一回事呢就像一个简单的示意图(inst实际上是一个实例已经包装成代理)。请注意,它只是说明越来越的属性;由于未修改的转发处理程序,所有其他操作仅由代理传递。

proxy diagram

代理代码可能如下:

function Test(a, b, c) { 
    this[0] = a; 
    this[1] = b; 
    this[2] = c; 

    this.length = 3; // needed for .slice to work 
} 

Test.prototype.foo = "bar"; 

Test = (function(old) { // replace function with another function 
         // that returns an interceptor proxy instead 
         // of the actual instance 
    return function() { 
    var bind = Function.prototype.bind, 
     slice = Array.prototype.slice, 

     args = slice.call(arguments), 

     // to pass all arguments along with a new call: 
     inst = new(bind.apply(old, [null].concat(args))), 
     //      ^is ignored because of `new` 
     //       which forces `this` 

     handler = new Proxy.Handler(inst); // create a forwarding handler 
              // for the instance 

    handler.get = function(receiver, name) { // overwrite `get` handler 
     if(name in inst) { // just return a property on the instance 
     return inst[name]; 
     } 

     if(name in Array.prototype) { // otherwise try returning a function 
            // that calls the appropriate method 
            // on the instance 
     return function() { 
      return Array.prototype[name].apply(inst, arguments); 
     }; 
     } 
    }; 

    return Proxy.create(handler, Test.prototype); 
    }; 
})(Test); 

var test = new Test(123, 456, 789), 
    sliced = test.slice(1); 

console.log(sliced);    // [456, 789] 
console.log("2" in test);   // true 
console.log("2" in sliced);  // false 
console.log(test instanceof Test); // true 
            // (due to second argument to Proxy.create) 
console.log(test.foo);    // "bar" 

转发处理器可在the official harmony wiki

Proxy.Handler = function(target) { 
    this.target = target; 
}; 

Proxy.Handler.prototype = { 
    // Object.getOwnPropertyDescriptor(proxy, name) -> pd | undefined 
    getOwnPropertyDescriptor: function(name) { 
    var desc = Object.getOwnPropertyDescriptor(this.target, name); 
    if (desc !== undefined) { desc.configurable = true; } 
    return desc; 
    }, 

    // Object.getPropertyDescriptor(proxy, name) -> pd | undefined 
    getPropertyDescriptor: function(name) { 
    var desc = Object.getPropertyDescriptor(this.target, name); 
    if (desc !== undefined) { desc.configurable = true; } 
    return desc; 
    }, 

    // Object.getOwnPropertyNames(proxy) -> [ string ] 
    getOwnPropertyNames: function() { 
    return Object.getOwnPropertyNames(this.target); 
    }, 

    // Object.getPropertyNames(proxy) -> [ string ] 
    getPropertyNames: function() { 
    return Object.getPropertyNames(this.target); 
    }, 

    // Object.defineProperty(proxy, name, pd) -> undefined 
    defineProperty: function(name, desc) { 
    return Object.defineProperty(this.target, name, desc); 
    }, 

    // delete proxy[name] -> boolean 
    delete: function(name) { return delete this.target[name]; }, 

    // Object.{freeze|seal|preventExtensions}(proxy) -> proxy 
    fix: function() { 
    // As long as target is not frozen, the proxy won't allow itself to be fixed 
    if (!Object.isFrozen(this.target)) { 
     return undefined; 
    } 
    var props = {}; 
    Object.getOwnPropertyNames(this.target).forEach(function(name) { 
     props[name] = Object.getOwnPropertyDescriptor(this.target, name); 
    }.bind(this)); 
    return props; 
    }, 

    // == derived traps == 

    // name in proxy -> boolean 
    has: function(name) { return name in this.target; }, 

    // ({}).hasOwnProperty.call(proxy, name) -> boolean 
    hasOwn: function(name) { return ({}).hasOwnProperty.call(this.target, name); }, 

    // proxy[name] -> any 
    get: function(receiver, name) { return this.target[name]; }, 

    // proxy[name] = value 
    set: function(receiver, name, value) { 
    this.target[name] = value; 
    return true; 
    }, 

    // for (var name in proxy) { ... } 
    enumerate: function() { 
    var result = []; 
    for (var name in this.target) { result.push(name); }; 
    return result; 
    }, 

    // Object.keys(proxy) -> [ string ] 
    keys: function() { return Object.keys(this.target); } 
};