public
Last active

Emulating ES.next private names in spidermonkey

  • Download Gist
private-names.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/*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)

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.