Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - John Resig's simple class instantiation and "use strict"

Reference : 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 );
  };
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 );
  };
}

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...