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

后端 未结 15 2755
北海茫月
北海茫月 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:57

    Yes.

    function _new(classConstructor, ...args) {
      var obj = Object.create(classConstructor.prototype);
      classConstructor.call(obj, ...args);
      return obj;
    }
    
    function test_new() {
      function TestClass(name, location) {
        this._name = name;
        this._location = location;
        this.getName = function() {
          return this._name;
        }
      }
    
      TestClass.prototype.getLocation = function() {
        return this._location;
      }
      TestClass.prototype.setName = function(newName) {
        this._name = newName;
      }
    
      const a = new TestClass('anil', 'hyderabad');
      const b = _new(TestClass, 'anil', 'hyderabad');
    
      const assert = console.assert
      assert(a instanceof TestClass)
      assert(b instanceof TestClass)
      assert(a.constructor.name === 'TestClass');
      assert(b.constructor.name === 'TestClass');
      assert(a.getName() === b.getName());
      assert(a.getLocation() === b.getLocation());
      a.setName('kumar');
      b.setName('kumar');
      assert(a.getName() === b.getName());
      console.log('All is well')
    }
    test_new()

    Ref: https://gist.github.com/aniltallam/af358095bd6b36fa5d3dd773971f5fb7

提交回复
热议问题