Skip to content

Instantly share code, notes, and snippets.

@aniltallam
Last active January 17, 2019 09:37
Show Gist options
  • Save aniltallam/af358095bd6b36fa5d3dd773971f5fb7 to your computer and use it in GitHub Desktop.
Save aniltallam/af358095bd6b36fa5d3dd773971f5fb7 to your computer and use it in GitHub Desktop.
Javascript HowItWorks: new, instanceOf etc implementations
// This will return an instance of the classConstructor, which is equalent to
// what we create using new keyword.
function _new (classConstructor, ...args) {
var obj = Object.create(classConstructor.prototype);
classConstructor.call(obj, ...args);
return obj;
}
// alternative to instanceOf
function _instanceOf (object, classConstructor) {
if (object === null) return false
if (object.__proto__ === classConstructor.prototype) return true
else return _instanceOf(object.__proto__, classConstructor) // check in the object's proto chain.
}
// alternative to Object.create
function _objectCreate (object) {
var obj = {
__proto__: object
}
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());
}
test_new()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment