Objects Flashcards
3 ways to create a blank object
{}
new Object
Object.create(null)
Count number of enumerable properties an object has
Object.keys( obj ).length
Test if object contains property/method, whether directly or in the prototype chain.
“field_name” in obj
Do not use obj.field_name
, as falsey values will evaluate to false. in
also has the added benefit of the properties not being evaluated, which could be negative on performance.
Test if object contains property/method directly (owns).
obj.hasOwnProperty(“field_name”);
How to remove a property/method from an object?
delete obj.field_name //=> true|false
(properties with “configurable” set to false cannot be removed, so false
would be returned. false
is also returned if the property doesn’t exist)
Dereferencing an object?
Dereferencing an object tells JS that you no longer need the object so the built-in garbage collector can free up the memory being used by that object. This happens automatically in JS, but you need to dereference the object first; the best way to do that is set the object pointer’s variable to null:
var o = {}; // do something o = null; // if there aren't any other pointers stored to a variable, JS will garbage collect it :)
3 ways to define a property (data-property)
(property fields must always be strings; if not observed, it is converted into a string)
o["prop"] = 1; o.prop = 1; // if the field name *could* be a valid variable name
// ECMAScript 5 way // (3rd argument is called "Property Descriptor") Object.defineProperty(o, "prop", { value: 1, // if a value can be reassigned writable: true, enumerable: true, // if prop can be deleted // and if you can modify "property descriptor" configurable: true, })
Make a child object of a parent object
var parent = {};
…
var child = Object.create(parent);
2 ways to access a property.
Test if property is enumerable
Object.prototype.propertyIsEnumerable(“field-name”);
[].propertyIsEnumberable(“length”) //=> false
Two types of properties.
Data properties & accessor properties.
Data properties contain a value. Accessor properties contain a getter and/or setter function.
2 ways to create an accessor property
Literal Syntax: { get getterProp() { return "J"; }, set setterProp(value) { console.log(value); } }
ES5 Method: Object.defineProperty(obj, "propName", { enumerable: true, configurable: true, get: function () { return "J"; }, set: function (value) { console.log(value); } })
Convention to indicate that property should be treated like it’s private (even if it’s still public)
Prepend with underscore
_privProp
What 2 attributes do data & accessor properties share in common?
enumerable & configurable
What are the default attributes if you use the literal property assignment method: obj.name = "value"
enumerable = true configurable = true writable = true