[removed] How to create a new instance of a class without using the new keyword?

后端 未结 6 2224
死守一世寂寞
死守一世寂寞 2020-12-25 13:22

I think the following code will make the question clear.

// My class
var Class = function() { console.log(\"Constructor\"); };
Class.prototype = { method: fu         


        
6条回答
  •  梦毁少年i
    2020-12-25 13:48

    Because JavaScript doesn't have classes, let me reword your question: How to create a new object based on an existing object without using the new keyword?

    Here is a method that doesn't use "new". It's not strictly a "new instance of" but it's the only way I could think of that doesn't use "new" (and doesn't use any ECMAScript 5 features).

    //a very basic version that doesn't use 'new'
    function factory(clazz) {
        var o = {};
        for (var prop in clazz) {
            o[prop] = clazz[prop];
        }
        return o;
    };
    
    //test
    var clazz = { prop1: "hello clazz" };
    var testObj1 = factory(clazz);
    console.log(testObj1.prop1);    //"hello clazz" 
    

    You could get fancy and set the prototype, but then you get into cross-browser issues and I'm trying to keep this simple. Also you may want to use "hasOwnProperty" to filter which properties you add to the new object.

    There are other ways that use "new" but sort of hide it. Here is one that borrows from the Object.create function in JavaScript: The Good Parts by Douglas Crockford:

    //Another version the does use 'new' but in a limited sense
    function factory(clazz) {
        var F = function() {};
        F.prototype = clazz;
        return new F();
    };
    
    //Test
    var orig = { prop1: "hello orig" };
    var testObj2 = factory(orig);
    console.log(testObj2.prop1);  //"hello orig"
    

    EcmaScript 5 has the Object.create method which will do this much better but is only supported in newer browsers (e.g., IE9, FF4), but you can use a polyfill (something that fills in the cracks), such as ES5 Shim, to get an implementation for older browsers. (See John Resig's article on new ES5 features including Object.create).

    In ES5 you can do it like this:

    //using Object.create - doesn't use "new"
    var baseObj = { prop1: "hello base" };
    var testObj3 = Object.create(baseObj);
    console.log(testObj3.prop1);
    

    I hope that helps

提交回复
热议问题