Create a gist now

Instantly share code, notes, and snippets.

@chikoski /new.js Secret
Last active Apr 28, 2017

What would you like to do?
An implemenation of new operator
function Point({x, y}){
this.x = x;
this.y = y;
}
Point.methods = {
distance: function(pt){
return Math.abs(pt.x - this.x) + Math.abs(pt.y - this.y);
},
norm: function(){
return this.x + this.y;
},
toString: function(){
return `(${this.x}, ${this.y})`;
}
};
function create(initializer, ...args){
const argList = Array.prototype.slice.apply(args);
const obj = {};
for(i in initializer.methods || {}){
obj[i] = initializer.methods[i];
}
initializer.apply(obj, argList);
obj.template = initializer;
return obj;
}
const kindOf = (obj, func) => obj.template === func;
function main(){
const zero = create(Point, {x: 0, y: 0});
const p = create(Point, {x: 10, y: 10});
console.log(`${zero} is a kind of Point: ${kindOf(zero, Point)}`);
console.log(`${p} is a kind of Point: ${kindOf(p, Point)}`);
console.log(`distance from ${zero} to ${p}: ${p.distance(zero)}`);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment