Note
Introduced in ECMAScript 5
Object.create(proto [, propertiesObject])
var o;
o = Object.create(null); //with no prototype
o = {};
// is equivalent to:
o = Object.create(Object.prototype);
function Constructor(){}
o = new Constructor();
// is equivalent to:
o = Object.create(Constructor.prototype);
o = Object.create({}, { p: { value: 42 } })
// by default properties ARE NOT writable, enumerable or configurable:
o.p = 24
o.p //42
o.q = 12
for (var prop in o) {
console.log(prop) //"q"
}
delete o.p //false
//to specify an ES3 property
o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });
Polyfill:
if (typeof Object.create !== 'function') {
Object.create = function (o, props) {
function F() {}
F.prototype = o;
if (typeof (props) === "object") {
for (prop in props) {
if (props.hasOwnProperty((prop))) {
F[prop] = props[prop];
}
}
}
return new F();
};
}
delete
prop in obj return true for own or inherited properties
obj.hasOwnProperty(prop) return false for inherited properties
obj.propertyIsEnumerable(prop) return true for own property and its enumerable attribute is true.
obj.prop!==undefined
for/in loops (enumerable):
for (p in o) {
if (!o.hasOwnProperty(p)) continue; //filter inherited properties
}
for (p in o) {
if (typeof o[p] === "function") continue; //filter methods
}
Note
Introduced in ECMAScript 5
Object.keys(obj) return enumerable own properties
Object.getOwnPropertyNames(obj) return enumerable and non-enumerable own properties
Note
Introduced in ECMAScript 5
Note
Introduced in ECMAScript 5
Object.getOwnPropertyDescriptor(obj, prop)
Object.defineProperty(obj, prop, descriptor)
In this case, this in the nested function is bound to the global object:
var o = {
value: 1,
outer: function () {
var inner = function () {
console.log(this); //bound to global object
};
inner();
}
};
o.outer();
Workaround:
var o = {
value: 1,
outer: function () {
var that = this; //assign this to a variable
var inner = function () {
console.log(that); //have access to outer's variable
console.log(that.value);
};
inner();
}
};
o.outer();
If return value is not specified, then undefined is returned. If the function is invoked with new and the return value is not an object, then this (the new object) is returned.
The true prototype of an object is held by [[Prototype]] internal property:
function Foo () {}
var bar = new Foo(); //the [[Prototype]] of bar is Foo.prototype
function Baz () {} //
Baz.prototype = new Foo(); //the [[Prototype]] of Baz.prototype is changed to Foo.prototype.
obj instanceof Constructor tests whether obj is in Constructor.prototype‘s prototype chain.
proto.isPrototypeOf(obj) tests whether obj is in proto‘s prototype chain.
Note
Introduced in ECMAScript 5
Object.getPrototypeOf(obj)
Warning
Not standard
obj.__proto__