John Resig的简单类实例化和"use strict"



参考:http://ejohn.org/blog/simple-class-instantiation/

// makeClass - By John Resig (MIT Licensed)
function makeClass(){
  return function(args){
    if ( this instanceof arguments.callee ) {
      if ( typeof this.init == "function" )
        this.init.apply( this, args.callee ? args : arguments );
    } else
      return new arguments.callee( arguments );
  };
}

我想知道,是否有任何符合ECMAScript 5的方式来实现相同的功能。问题是,在严格模式下不赞成访问arguments.callee

据我所知,arguments.callee在严格模式下不会被弃用,在这种情况下,您可以继续使用它;相反,它已被删除,并且尝试使用将(或应该)引发异常。

如果你不介意这种矛盾修饰法的话,解决方法是使用命名的匿名函数。实际上,我应该说"命名函数表达式"。一个例子:

function someFunc(){
  return function funcExpressionName(args){
    if (this instanceof funcExpressionName) {
      // do something
    } else
      return new funcExpressionName( arguments );
  };
}

在我的示例中,您提供的名称funcExpressionName不应该从任何地方访问,除非在它所应用的函数内部,但不幸的是,IE有其他想法(如果您在谷歌上搜索它,可以看到)。

对于您问题中的示例,我不确定如何处理args.callee,因为我不知道调用函数是如何设置的,但根据我的示例,arguments.callee的使用将被替换。

nnnnnn给出的上述想法非常好。为了避免IE问题,我建议以下解决方案。

function makeClassStrict() {
    var isInternal, instance;
    var constructor = function(args) {
        // Find out whether constructor was called with 'new' operator.
        if (this instanceof constructor) {
            // When an 'init' method exists, apply it to the context object.
            if (typeof this.init == "function") {
                // Ask private flag whether we did the calling ourselves.
                this.init.apply( this, isInternal ? args : arguments ); 
            }
        } else {
            // We have an ordinary function call.
            // Set private flag to signal internal instance creation.
            isInternal = true;                                           
            instance = new constructor(arguments);
            isInternal = false;                                         
            return instance;
        }
    };
    return constructor;
}

请注意,我们如何通过使用内部标志来避免在// do something部分中引用args.callee

John Resig的原始代码使用无参数构造函数失败。
var Timestamp = makeClass();
Timestamp.prototype.init = function() {
    this.value = new Date();
};
// ok
var timestamp = Timestamp();
alert( timestamp.value );  
// TypeError: args is undefined
var timestamp = new Timestamp();
alert( timestamp.value );   

但可以使用以下线路进行修复

this.init.apply( this, args && args.callee ? args : arguments );

最新更新