Can I construct a JavaScript object without using the new keyword?

后端 未结 15 2596
北海茫月
北海茫月 2020-11-27 16:04

Here is what I\'d like to do:

function a() {
  // ...
}
function b() {
  //  Some magic, return a new object.
}
var c = b();

c instanceof b // -> true
c          


        
相关标签:
15条回答
  • 2020-11-27 17:02

    The simple answer to your specific question is: no.

    It would help you identified why you want to avoid new. Perhaps the patterns alluded to by one of the other answers will help. However none of them result in the instanceof returning true in your tests.

    The new operation is essentially:-

    var x = (function(fn) { var r = {}; fn.call(r); return r;}(b);
    

    However there is the difference that the constructing fn is attached to the object using some internal property (yes you can get it with constructor but setting it doesn't have the same effect). The only way to get instanceof to work as intended is to use the new keyword.

    0 讨论(0)
  • 2020-11-27 17:04

    You can't avoid new in the general case (without going to extremes, as per the Crockford article Zoidberg indirectly linked to) if you want inheritance and instanceof to work, but then (again), why would you want or need to?

    The only reason I can think of where you'd want to avoid it is if you're trying to pass a constructor function to another piece of code that doesn't know it's a constructor. In that case, just wrap it up in a factory function:

    function b() {
        // ...
    }
    function makeB() {
        return new b();
    }
    var c = makeB();
    
    0 讨论(0)
  • 2020-11-27 17:06

    The only way to get instanceof to work is to use the new keyword. instanceof exploits ____proto____ which is established by new.

    0 讨论(0)
提交回复
热议问题