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
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