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

Viewed 35349

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 instanceof a // -> true
b instanceof a // -> true

Is it possible? I can make b be an instance of a easily by hooking a into its prototype chain but then I have to do new b(), which is what I'm trying to avoid. Is what I want possible?

Update: I feel that it might be possible with judicious use of b.__proto__ = a.prototype. I'm going to experiment more after work.

Update 2: Below is what seems to be the closest you can get, which is good enough for me. Thanks all for the interesting answers.

function a() {
  // ...
}
function b() {
  if (!(this instanceof arguments.callee)) {
    return new arguments.callee();
  }
}
b.__proto__ = a.prototype

var c = b();
c instanceof b // -> true
c instanceof a // -> false
b instanceof a // -> true

Update 3: I found exactly what I wanted in a blog post on 'power constructors', once I added the essential b.__proto__ = a.prototype line:

var object = (function() {
     function F() {}
     return function(o) {
         F.prototype = o;
         return new F();
     };
})();

function a(proto) {
  var p = object(proto || a.prototype);
  return p;
}

function b(proto) {
  var g = object(a(proto || b.prototype));
  return g;
}
b.prototype = object(a.prototype);
b.__proto__ = a.prototype;

var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
a() instanceof a // -> true
14 Answers

You can use this pattern:

function SomeConstructor(){
   if (!(this instanceof SomeConstructor)){
        return new SomeConstructor();
   }
   //the constructor properties and methods here
}

after which you can do:

var myObj = SomeConstructor();

In addition to this (rather old) answer: you can use a module pattern to create an object:

function Person(name, age, male) {
  name = name || 'unknown';
  age = age || 0;
  function get() {
    return ['This person is called ', name,
            (!male ? ', her' : ', his'),' age is ',
            age].join('');
  }
  function setAge(nwage) {
     age = nwage;
  }
  return Object.freeze({get: get, setAge: setAge});
}
// usage
var jane =  Person('Jane', 23)
   ,charles = Person('Charles', 32, 1)
   ,mary = Person('Mary', 16);

console.log(jane.get()); //=> This person is called Jane, her age is 23
mary.setAge(17);
console.log(mary.get()); //=> This person is called Mary, her age is 17

Here's a jsFiddle for some Date functionallity I created using that pattern.

Yes. If you don't want to use the 'new' keyword, just use prototype, and return something in your constructor function.

Using 'new' just tells the constructor functions that:

  1. The 'this' keyword in the constructor function should reference the function itself, not the parent object (as per usual), which would be the window object if this function was declared in the global scope.

  2. For all failed lookups (obj properties not found) on the newly created object/instance, check the original constructor function's prototype property.

So with new:

    function Point(x, y) {
       this.x = x;
       this.y = y;
    }
    Point.prototype.getDistance = function(otherPoint){
       var Dx = (this.x - otherPoint.x) ** 2;
       var Dy = (this.y - otherPoint.y) ** 2;
       var d = Dx + Dy;
       d = Math.sqrt(d);
       return d
    }
    var pointA = new Point(3, 6);
    var pointB = new Point(5, 8);
    var distanceAB = pointA.getDistance(pointB);

Without new:

    function Point(x, y) {
       let d = Object.create(Point.prototype);
       d.x = x;
       d.y = y;
       return d
    }
    Point.prototype.getDistance = function(otherPoint){
       var Dx = (this.x - otherPoint.x) ** 2;
       var Dy = (this.y - otherPoint.y) ** 2;
       var d = Dx + Dy;
       d = Math.sqrt(d);
       return d
    }
    var pointA = Point(3, 6);
    var pointB = Point(5, 8);
    var distanceAB = pointA.getDistance(pointB);

Try adding removing the 'new' in the the first example, and you'll see the 'this', no longer refers to the constructor function, but the window object instead. You'll be giving your window x and y properties, which proplably isn't what you want.

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.

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();

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

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

Polyfill for new operator:

function sampleClass() {
    this.cname = "sample";
}

sampleClass.prototype.getCname = function() {
    return this.cname;
}

const newPolyfill = function(fname) {
    if (typeof fname !== "function")
    throw Error("can't call new on non-functional input");

    let newFun = {};
    newFun.__proto__ = Object.assign(fname.prototype);
    fname.prototype.constructor();

    for (let key in fname.prototype) {
        if (typeof fname.prototype[key] !== "function") {
        newFun[key] = fname.prototype[key];
        delete newFun.__proto__[key];
        delete fname.__proto__[key];
       }
    }

    return newFun;
}

let newObj = new sampleClass();
console.log("new obj", newObj);
console.log("new cname", newObj.getCname());//sample
let newPolyObj = newPolyfill(sampleClass);
console.log("new poly obj", newPolyObj);
console.log("newPly cname", newPolyObj.getCname());//sample
console.log(newPolyObj instanceof(sampleClass)) // true
Related