Skip to content

Instantly share code, notes, and snippets.

@Gozala
Created January 30, 2012 21:01
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 Gozala/1706668 to your computer and use it in GitHub Desktop.
Save Gozala/1706668 to your computer and use it in GitHub Desktop.
Emulating ES.next private names in spidermonkey
/*jshint asi:true */
!(function(getOwnNames, getKeys, nil) {
function ignore() {}
function nonPrivate(name) { return name[0] !== '\\' }
Object.defineProperties(Object, {
getOwnPropertyNames: { value: (function(object) {
return getOwnNames(object).filter(nonPrivate)
}).bind(null) },
keys: { value: (function(object) {
return getKeys(object).filter(nonPrivate)
}).bind(null) }
})
Object.defineProperty(Object.prototype, '__iterator__', {
value: function iterator(names) {
let iteratee = Object.create(this, { '__iterator__': { value: nil } })
for (let name in iteratee) {
if (nonPrivate(name))
yield names ? name : iteratee[name]
}
}
})
})(Object.getOwnPropertyNames, Object.keys)
function Name() {
return Object.create(Name.prototype, {
toString: {
value: String.bind(null, '\\' + Math.round(Math.random() * 1000000000000))
}
})
}
function props(object) {
var result = []
for (let key in object) result.push(key)
return result
}
var bar = new Name()
var a = { foo: 'foo!' }
a[bar] = 'bar'
Object.keys(a)
Object.getOwnPropertyNames(a)
props(a)
var b = Object.create(a)
Object.keys(b)
Object.getOwnPropertyNames(b)
props(b)
@Gozala
Copy link
Author

Gozala commented Jan 30, 2012

Only issue with this approach is that if one creates Object.create(yourObject, { __iterator__: { value: undefined } }) he will be able to gain access to all private names and properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment