Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save itrelease/367140 to your computer and use it in GitHub Desktop.
Save itrelease/367140 to your computer and use it in GitHub Desktop.
/**
* Aliases and additional "sugar"
* 2010-04-15
* @author Dmitry A. Soshnikov
*/
(function () {
["defineProperty", "defineProperties", "keys", "getOwnPropertyNames",
"getOwnPropertyDescriptor", "getPrototypeOf", "seal", "freeze",
"preventExtensions", "isFrozen", "isSealed", "isExtensible"]
.forEach(function (methodName) {
var newMethodName = (
methodName == "getPrototypeOf"
? "getPrototype"
: methodName
);
Object.defineProperty(Object.prototype, newMethodName, {
// use function (as in spec), but for some properties -
// getter is better, e.g. o.keys - for what to make it as a method?
value: function () {
return Object[methodName].apply(
Object,
[this].concat([].slice.call(arguments))
);
},
// descriptor values
enumerable: false,
writable: false,
configurable: false
});
});
/**
* forAll
* iterates over all properties of an object
* including those with [[Enumerable]] false,
* analysing prototype chain as well
*/
Object.defineProperty(Object.prototype, "forAll", {
value: function (fn) {
var
self = this,
object = self;
do {
object.getOwnPropertyNames().forEach(function (name) {
if (!fn.call(
self, // reciever
name, // property name
object[name], // value
object, // real owner
object.getOwnPropertyDescriptor(name).enumerable // is it enumerable
))
return false;
});
} while (object = object.getPrototype());
},
// descriptor
enumerable: false,
writable: false,
configurable: false
});
})();
var o = {x: 10, y: 20};
o.defineProperty("z", {
value: 100,
enumerable: false
});
print(o.keys()); // x,y, but not z
print(o.z); // 100
print(o.getOwnPropertyNames()); // x,y,z
print(o.getOwnPropertyDescriptor("z").enumerable); // false
print(o.seal());
print(o.isSealed()); // true
// show all properties of an object
// including inherited and with {enumerable: false}
o.forAll(function (name, value, realOwner, enumerable) {
print('Property "' + name +'" with value ' + value + "\n");
// test for real owner
realOwner != this && print("\t- " + name + " property is inherited\n");
// and show [[Enumerable]] false properties
!enumerable && print("\t- " + name + " isn't enumerable\n");
});
var object = Object.create(o)
.preventExtensions();
print(object.isExtensible()); // false
print(object.getPrototype() === o); // true
print(o.isPrototypeOf(object)); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment