Created
July 21, 2015 16:55
-
-
Save keithwhor/cd3784529b70f9627097 to your computer and use it in GitHub Desktop.
Basic Unit class for graphs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Unit { | |
// Entity is used as node or edge type, for different classifications | |
// i.e. 'person', 'game', 'road', etc. | |
constructor(entity, properties) { | |
this.entity = entity + ''; | |
this.load(properties || {}); | |
} | |
// load properties (id, name, age, etc.) from an object | |
load(properties) { | |
let p = Object.create(null); | |
Object.keys(properties).forEach(function(v) { | |
p[v] = properties[v]; | |
}); | |
this.properties = p; | |
return this; | |
} | |
set(property, value) { | |
return this.properties[property] = value; | |
} | |
unset(property) { | |
return delete this.properties[property]; | |
} | |
has(property) { | |
return Object.prototype.hasOwnProperty.call(this.properties, property); | |
} | |
get(property) { | |
return this.properties[property]; | |
} | |
toString() { | |
return [this.constructor.name, ' (', this.entity, ' ', JSON.stringify(this.properties) ,')'].join(''); | |
} | |
} |
Okay, now I see you're using Object.create(null)
, what's the advantage of using this instead of creating an object with Object
as it's prototype? Is there some real-life example of how it would be useful? Is it some kind of optimization? Thanks!
(Couldn't edit my last comment, getting an empty error)
Also, as long you're not inheriting anything, any property is actually an own property, so why not use the in
operator:
return (property in this.properties);
You can use the default value in parameter
14| load(properties = {})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I'm curious why did you call Object.prototype on line 44 instead of
Good article btw!