Created
January 30, 2012 21:01
-
-
Save Gozala/1706668 to your computer and use it in GitHub Desktop.
Emulating ES.next private names in spidermonkey
This file contains 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
/*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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.