Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

prototype programming - Is there a good use case for the constructor property in Javascript?

First off, this question is not "what does the constructor property do?" - There's plenty of good documentation on exactly what it is and how it works: It's a reference to the function that created the object (which may be inherited from its prototype).

I'm more interested in knowing common use-cases for this property. It seems all good in theory, but when would you actually need a reference to the function that constructed your object? A few ideas would be:

  • Perhaps I want to clone it. I could call the constructor again and
    get another instance of my object. This of course wouldn't work well since you'd potentially be creating an instance of your object's
    prototype, not the object itself; plus a much preferred method would be to create a new object and set that object's prototype instead.
  • Perhaps you can use it to figure out what the "type" of the object is. This seems rather odd, since you can use instanceof or Object.prototype.toString() instead.
  • Can you change or re-assign the constructor? Would there ever be a good reason to do this?

Hopefully some people can chime in with some good Javascript paterns that make use of the constructor reference, or provide an official explanation for why the property exists.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

One case where the constructor property is handy (or would be if it was reliable) is where a function needs to know the type of argument it has been passed, e.g.

function foo(arg) {
  if ( /* if arg is an array */ ) {
    // deal with array
  } else if ( /* if arg is an object */ ) {
    // deal with object
  }
}

If the above function is passed an array or object, then typeof will return object in both cases. The constructor property can be used:

  if ( arg.constructor == Array )

But that fails if the array is created in a different frame to where the test is taking place (i.e. it's Array constructor is a different object to the Array function in the scope of the test).

So if you rule out frames (or other cases where scope is an issue), then the constructor property is fine to use for this.

But that does not fix the general issue of the constructor property being writable (and therefore can be set to anything) and cases where the prototype chain is more than trivial.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...