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

后端 未结 15 2795
北海茫月
北海茫月 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 16:44

    For those, who may find this via Google (like me...), I developed the original solution further for a better common usage:

    var myObject = function() {}; // hint: Chrome debugger will name the created items 'myObject'
    
    var object = (function(myself, parent) {  
         return function(myself, parent) {
             if(parent){
                 myself.prototype = parent;
             }
             myObject.prototype = myself.prototype;
             return new myObject();
         };
    })(); 
    
    a = function(arg) {
         var me = object(a);
         me.param = arg;
         return me;
    };
    
    b = function(arg) {
        var parent = a(arg),
            me = object(b, parent)
        ;
        return me;
    };
    
    var instance1 = a();
    var instance2 = b("hi there");
    
    console.log("---------------------------")
    console.log('instance1 instance of a: ' +  (instance1 instanceof a))
    console.log('instance2 instance of b: ' +  (instance2 instanceof b))
    console.log('instance2 instance of a: ' +  (instance2 instanceof a))
    console.log('a() instance of a: ' +  (a() instanceof a))
    console.log(instance1.param)
    console.log(instance2.param)

提交回复
热议问题