
In JavaScript, almost all objects are instances of Object type, and they inherit properties and methods from Object.prototype
.
Although most properties are shadowed or overridden, and Object can be created intentionally, This object is not a “real object”.
Object initialization (increment)
Objects can be initialized by new Object()
and Object.create()
, or by using a initialization token
Constructor:new Object() , the constructor wraps the given value into a new object
If the given value is null
or undefined
, it creates and returns an empty object
let emptyObject = new Object() // {}
let emptyObject = new Object(undefined) // {}
let emptyObject = new Object(null) // {}
const valueObject1 = new Object({"name":"mwellvae"})
console.log(valueObject1) //{name: 'mwellvae'}
const valueObject2 = new Object()
valueObject.name = "mwell"
console.log(valueObject2) // {name: 'mwell'}
Code language: JavaScript (javascript)
Static method
1. Object.assign
Syntax: Object.assign(target, …sources), will not throw an error when the object value is null
or undefined
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnTarget = Object.assign(target, source);
console.log(target) // {a: 1, b: 4, c: 5}
console.log(returnTarget) // {a: 1, b: 4, c: 5}
console.log(source) //{ b: 4, c: 5 }
Code language: JavaScript (javascript)
Object.assign()
creates a new object by copying one or more objects. The object copying created by Object.assign()
is a shallow copy, and only the property value is copied. If the source object is a reference to an object, it only copies its reference value.
let obj = {a: 1, b: { c: 0}}
let newObj = Object.assign({}, obj)
console.log(newObj)
obj.a = 3
console.log(obj) // {a: 3, b: { c: 0}}
console.log(newObj) // {a: 1, b: { c: 0}}
obj.b.c = 2
console.log(obj) // {a: 3, b: { c: 2}}
console.log(newObj) // {a: 1, b: { c: 2}}
let deepObj = JSON.parse(JSON.stringify(obj))
obj.a = 4
obj.b.c = 4
console.log(JSON.stringify(obj3)) // {"a":3,"b":{"c":2}}
console.log(obj) // {"a":4,"b":{"c":4}}
Code language: JavaScript (javascript)
2. Object.create
Syntax: Object.create(proto) or Object.create(proto, propertiesObject). The method Object.create() is used to create a new object, using the existing object as the prototype of the newly created object
const person = {
name: 'person',
printIntroduction: function() {
console.log('this':this)
}
}
console.log(person.printIntroduction())
const mine = Object.create(person)
console.log(person.printIntroduction())
mine.name = 'mine'
console.log(mine.printIntroduction()
Code language: JavaScript (javascript)
All primitive types except null and undefinedhave their corresponding wrapper objects
String: String base type
Number: Numeric primitive types
BigInt: big integer primitive type
Boolean: Boolean primitive type
Symbol: literal primitive type
When using a null
prototyped object, the null
prototyped object has unpredictable behavior because it does not inherit any object methods from Object.prototype
. And the lack of Object.prototype.toString()
methods often makes debugging very difficult
const normalObj = {};
const nullProtoObj = Object.create(null)
console.log(normalObj) // {}
console.log(nullProtoObj) // {}
console.log("" + normalObj) // [object Object]
console.log("" + nullProtoObj) // Error
alert(normalObj); // [object Object]
alert(nullProtoObj) // Error
normalObj.valueOf() // shows {}
nullProtoObj.valueOf() // Error
normalObj.hasOwnProperty("p") // "false"
nullProtoObj.hasOwnProperty("p") //Error
normalObj.constructor // "Object() { [native code] }"
nullProtoObj.constructor // "undefined"
Code language: JavaScript (javascript)
You can add toString
methods to objects whose prototype is null
, like this:
nullProtoObj.toString = Object.prototype.toString; //
console.log(nullProtoObj.toString()); // "[object Object]"
console.log("nullProtoObj is: " + nullProtoObj); // "nullProtoObj is: [object Object]"
Code language: JavaScript (javascript)
In practice null
prototyped objects are often used as map replacements. Because the existence of the prototype’s own properties can lead to some errors
const ages = { 'Edwin': 18, 'Robert': 27 };
function hasPerson(name) {
return name in ages;
}
function getAge(name) {
return ages[name];
}
hasPerson('Robert') //true
getAge('Robert') // 27
hasPerson("hasOwnProperty") // true
getAge("toString") // ƒ toString() { [native code] }
Code language: JavaScript (javascript)
Using null-prototype
objects eliminates this potential problem and doesn’t introduce too much complex logic into the hasPerson
and getAge
function
const ages = Object.create(null, {
'Edwin': { value: 18, enumerable: true },
'Robert': { value: 27, enumerable: true },
});
function hasPerson(name) {
return name in ages;
}
function getAge(name) {
return ages[name];
}
hasPerson('Robert') //true
getAge('Robert') // 27
hasPerson("hasOwnProperty") // false
getAge("toString") // undefined
Code language: JavaScript (javascript)
Objects that do not inherit Object.prototype
prototype methods also prevent prototype pollution attacks. If a malicious script adds a property to Object.prototype
, that property will be accessible to every object in the program, and objects with null
as prototypes will not be affected
Object property deletion (delete)
Object itself does not provide a method to delete its own properties (Map.prototype.delete()
can delete its own properties). In order to delete a property on an object, one must use delete
opertor
delete on map prototype
const willDeleteMap = new Map()
willDeleteMap.set('name', 'value')
console.log(willDeleteMap.delete('name')) // true
console.log(willDeleteMap.has('name')) // false
Code language: JavaScript (javascript)
delete operator
const willDeleteMap = {
firstname: 'Jim',
lastname: 'Green'
}
delete willDeleteMap.firstname
console.log(willDeleteMap)
console.log(willDeleteMap.firstname)// undefined
Code language: JavaScript (javascript)
Compare objects
Syntax:Object.is(value1, value2)
Object.is()
, the method determines whether two values are the same value. Object.is
will not coerce the values on both sides,
// Case 1
Object.is(25, 25); // true
Object.is('foo', 'foo'); // true
Object.is('foo', 'bar'); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false
// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true
Object.is(0n, -0n); // true
// Case 3: NaN
Object.is(NaN, 0/0); // true
Object.is(NaN, Number.NaN) // true
Code language: JavaScript (javascript)
Freeze objects Object.freeze()
Syntax:Object.freeze(obj)
Object.freeze()
method is used to freeze an object. A frozen object can no longer be modified; when an object is frozen, new properties cannot be added to the object, existing properties cannot be deleted, and the enumerability, configurability, and writability of existing properties of the object cannot be modified. Cannot modify the value of an existing property.
After freezing an object, the object’s prototype cannot be modified either. freeze()
Returns the same object as passed in
const freezeObj = {
prop: function() {},
foo: 'bar',
childObj: {},
childArr: []
}
freezeObj.foo = 'Foo after first change'
delete freezeObj.prop
freezeObj.childArr.push(0)
freezeObj.addChild = "Data added"
console.log(freezeObj) // {foo: 'Foo after first change', childObj: {…}, childArr: Array(1), addChild: 'Data added'}
const newObj = Object.freeze(freezeObj);
newObj === freezeObj // true,
newObj.foo = '2nd change, not changed'
newObj.childArr.push('2nd, can change,freeze only for 1st layer')
newObj.addNewChild = "2nd add,not added"
newObj.childObj.addName = "Can change object data"
console.log(newObj)
Code language: JavaScript (javascript)
To make an object immutable, you can recursively freeze each property of type object (deep freeze)