John Resig的简单类实例化和“use strict” [英] John Resig's simple class instantiation and "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
。
I was wondering, if there are any ECMAScript 5 compliant way to implement the same functionality. The problem is, accessing arguments.callee
is deprecated in strict mode.
推荐答案
据我所知, arguments.callee
在严格模式下不被弃用,在这种情况下你可以继续使用它;相反,它已被删除并尝试使用将(或应该)抛出异常。
As I understand it arguments.callee
isn't deprecated in strict mode, in which case you could continue to use it; rather, it has been removed and attempted use will (or is supposed to) throw an exception.
解决方法是使用命名的匿名函数如果你原谅矛盾的话。我应该说命名函数表达式。例如:
The workaround is to use named anonymous functions, if you'll forgive the oxymoron. Really I should say "named function expressions". An example:
function someFunc(){
return function funcExpressionName(args){
if (this instanceof funcExpressionName) {
// do something
} else
return new funcExpressionName( arguments );
};
}
您提供的名称,在我的示例中 funcExpressionName
不应该从其应用的函数内部的任何地方访问,但不幸的是IE有其他想法(如你 Google it 。
The name you provide, in my example funcExpressionName
is not supposed to be accessible from anywhere except inside the function it applies to, but unfortunately IE has other ideas (as you can see if you Google it).
对于你问题中的例子我我不知道如何处理 args.callee
因为我不知道调用函数是如何设置的,而是使用参数.callee
将根据我的例子进行替换。
For the example in your question I'm not sure how to handle the args.callee
since I don't know how that is set by the calling function, but the use of arguments.callee
would be replaced as per my example.
这篇关于John Resig的简单类实例化和“use strict”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!