Skip to content

Instantly share code, notes, and snippets.

@chikoski

chikoski/new.js Secret

Last active April 28, 2017 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chikoski/1a1fab7e66005b167504da92396333a3 to your computer and use it in GitHub Desktop.
Save chikoski/1a1fab7e66005b167504da92396333a3 to your computer and use it in GitHub Desktop.
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