“Advanced Front End Foundation” JS-Object Function Details

  javascript

clipboard.png

Object.assign(target,source1,source2,…)

This method is mainly used for merging objects, merging all enumerable attributes of the source object Source onto the target object Target. This method copies only the source object’s own attributes, not inherited attributes.
The Object.assign method implements a shallow copy instead of a deep copy. In other words, if the value of an attribute of the source object is an object, the copy of the target object gets a reference to this object. Attributes with the same name will be replaced.

Object.assign can only copy values. If the value to be copied is a value-taking function, it will be evaluated and then copied.

Object.assign can be used to process arrays, but will treat arrays as objects.

const target = {
 x : 0,
 y : 1
 };
 const source = {
 x : 1,
 z : 2 ,
 fn : {
 number : 1
 }
 };
 Object.assign(target, source);
 //target {x: 1, y: 1, z: 2, fn: {number: 1}}//attributes with the same name will be overwritten
 // source  {x : 1, z : 2, fn : {number : 1}}
 target.fn.number = 2;  //Copy as Object Reference
 // source  {x : 1, z : 2, fn : {number : 2}}
 
 
 function Person(){
 this.name = 1
 };
 Person.prototype.country = 'china';
 let student = new Person();
 student.age = 29 ;
 const young = {insterst : 'sport'};
 Object.assign(young,student);
 //young {instest:' sport', age: 29, name: 1}//can only copy its own attributes, not prototype
 
 
 Object.assign([1, 2, 3], [4, 5]) // treats arrays as objects
 // [4, 5, 3]

Object.create(prototype[,propertiesObject])

Creates a new object using the specified prototype object and its attributes

var parent = {
 x : 1,
 y : 1
 }
 var child = Object.create(parent,{
 Z: {// z will become the attribute of the created object
 writable:true,
 configurable:true,
 value: "newAdd"
 }
 });
 console.log(child)

clipboard.png


Object.defineProperties(obj,props)

Define new attributes or modify existing attributes directly on an object and return the object.

var obj = {};
 Object.defineProperties(obj, {
 'property1': {
 value: true,
 writable: true
 },
 'property2': {
 value: 'Hello',
 writable: false
 }
 // etc. etc.
 });
 console.log(obj)   // {property1: true, property2: "Hello"}

Object.defineProperty(obj,prop,descriptor)

Define a new attribute on an object, or modify an existing attribute of an object and return the object.

Object.defineProperty(obj, 'is', {
 value: function(x, y) {
 if (x === y) {
 //For the case that +0 is not equal to -0
 return x !  == 0 || 1 / x === 1 / y;
 }
 //According to NaN's situation
 return x !  == x && y !  == y;
 },
 Configurable: true, // can be deleted
 Enumerable: false, // whether forin enumeration is allowed
 Writable: true // Is it read-only
 });
 console.log(obj)
 
 //Note that you cannot set (writable, value) and get, set methods at the same time, otherwise the browser will report an error: invalid propertydescriptor.cannotbothspecify accessors and avaluorwritable attribute.

Object.getOwnPropertyDescriptor()

Functions:
This method returns the attribute descriptor corresponding to the last owned attribute on the specified object. (Self-owned attributes refer to attributes that are directly assigned to the object and do not need to be searched from the prototype chain)

Syntax: object.getownpropertydescriptor (obj, prop)
Obj: Target Object to Find
Prop: attribute name within target object

var person = {
 Name:' Zhang San',
 age: 18
 }
 
 var desc = Object.getOwnPropertyDescriptor(person, 'name');
 Log (desc) results are as follows
 // {
 //     configurable: true,
 //     enumerable: true,
 //     writable: true,
 // value: "Zhang San"
 // }

ps

The two methods of defineProperty and defineProperties of Object are very important in js. Their main function is to define or modify these internal properties. The corresponding getOwnPropertyDescriptors and GetOWNPropertyDescriptors are the descriptions of the internal properties in this line.

For example

Adds an access descriptor attribute to the object
 var obj = {};
 var aValue;  //If the variable is not initialized and the following A attribute is not set, direct reading will report an error aValue is not defined
 var b;
 Object.defineProperty(obj, 'a', {
 configurable : true,
 enumerable : true,
 get: function() {
 return aValue
 },
 set: function(newValue) {
 aValue = newValue;
 b = newValue + 1
 }
 })
 console.log(b) // undefined
 Console.log(obj.a) // undefined, when reading attribute value, call get method to return undefined
 obj.a = 2;  //when setting the attribute value, call the set method, aValue is 2
 
 Console.log(obj.a) // 2 reads the attribute value and calls the get method, when aValue is 2
 When console.log(b) // 3 assigns value to obj.a again, set method is executed, and the value of b is modified to 2. in addition, the calculation attribute in vue is realized by setter

This is the core of vue

Simple Data Bidirectional Binding

Html code:

<body>
 <p>
 input1=><input type="text" id="input1">
 </p>
 <p>
 input2=>
 <input type="text" id="input2">
 </p>
 <div>
 I add 1= > to the value of input1 each time.
 <span id="span"></span>
 </div>
 </body>
 Js code:
 
 var oInput1 = document.getElementById('input1');
 var oInput2 = document.getElementById('input2');
 var oSpan = document.getElementById('span');
 var obj = {};
 Object.defineProperties(obj, {
 val1: {
 configurable: true,
 get: function() {
 oInput1.value = 0;
 oInput2.value = 0;
 oSpan.innerHTML = 0;
 return 0
 },
 set: function(newValue) {
 oInput2.value = newValue;
 oSpan.innerHTML = Number(newValue) ?  Number(newValue) : 0
 }
 },
 val2: {
 configurable: true,
 get: function() {
 oInput1.value = 0;
 oInput2.value = 0;
 oSpan.innerHTML = 0;
 return 0
 },
 set: function(newValue) {
 oInput1.value = newValue;
 oSpan.innerHTML = Number(newValue)+1;
 }
 }
 })
 oInput1.value = obj.val1;
 oInput1.addEventListener('keyup', function() {
 obj.val1 = oInput1.value;
 }, false)
 oInput2.addEventListener('keyup', function() {
 obj.val2 = oInput2.value;
 }, false)

Object.keys(obj)

Returns an array composed of the enumerable attributes of a given object. The order of the attribute names in the array is the same as that returned when traversing the object using the for…in loop (the main difference between the two is that a for-in loop enumerates the attributes on its prototype chain).

let arr = ["a", "b", "c"];
 console.log(Object.keys(arr));
 // ['0', '1', '2']
 
 /* Object Object */
 let obj = { foo: "bar", baz: 42 },
 keys = Object.keys(obj);
 console.log(keys);
 // ["foo","baz"]

Object.values()

The method returns an array of all enumerable attribute values for a given object in the same order as using the for…in loop (except that the for-in loop enumerates the attributes in the prototype chain).

Values filters the attribute named Symbol value.

var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
 console.log(Object.values(an_obj));  // ['b', 'c', 'a']
 
 var obj = { 0: 'a', 1: 'b', 2: 'c' };
 console.log(Object.values(obj));  // ['a', 'b', 'c']

Object.entries()

Returns an array of key-value pairs for a given object’s own enumerable attributes, arranged in the same order as when traversing the object using the for…in loop (except that the for-in loop also enumerates attributes in the prototype chain).

const obj = { foo: 'bar', baz: 42 };
 console.log(Object.entries(obj));  // [ ['foo', 'bar'], ['baz', 42] ]
 
 const simuArray = { 0: 'a', 1: 'b', 2: 'c' };
 console.log(Object.entries(simuArray));  // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

HasOwnProperty () determines whether the specified attribute exists in the object’s own attribute.
obj.hasOwnProperty(‘name’)

Object.getOwnPropertyDescriptor(obj,prop)

Returns the attribute descriptor corresponding to the last owned attribute on the specified object. (Self-owned attributes refer to attributes that are directly assigned to the object and do not need to be searched from the prototype chain).

If the specified property exists on the object, its property descriptor object is returned; otherwise, undefined is returned.

var arr = ['name','age'] ;
 arr.forEach(val => console.log(Object.getOwnPropertyDescriptor(obj,val)))
 
 // {value: "js", writable: true, enumerable: true, configurable: true}
 // undefined

Object.getOwnPropertyDescriptors(obj)

Gets the descriptor of all of an object’s own attributes.

var obj = {
 name : 'js',
 age : 20
 }
 console.log(Object.getOwnPropertyDescriptors(obj))
 
 const source = {
 set foo(value) {
 console.log(value);
 }
 };
 
 const target2 = {};
 Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source));
 Object.getOwnPropertyDescriptor(target2, 'foo')
 
 
 const obj = Object.create(
 some_obj,
 Object.getOwnPropertyDescriptors({
 foo: 123,
 })
 );

Object.getOwnPropertyNames()

Returns an array of attribute names (including attributes that are not enumerable but do not include Symbol values as names) for all of the specified object’s own attributes.

var obj = { 0: "a", 1: "b", 2: "c"};
 
 Object.getOwnPropertyNames(obj).forEach(function(val) {
 console.log(val);
 });
 
 
 var obj = {
 x : 1,
 y : 2
 }
 
 Object.defineProperty(obj,'z',{
 enumerable : false
 })
 Console.log (object.getownpropertynames (obj))//["x", "y", "z"] contain non-enumerable attributes.
 Console.log (object.keys (obj))//["x", "y"] contains only enumerable attributes.

Object.getOwnPropertySymbols()
Returns an array of all Symbol attributes for a given object itself.


Object.getPrototypeOf()
Returns the prototype of the specified object (the value of the internal [[Prototype]], that is, _ prototype _ _, instead of the prototype of the object).


Object.isPrototypeOf()
Judge whether an object exists on the prototype chain of another object.


Object.setPrototypeOf(obj,prototype)
Sets the prototype object for the object


Object.is()

Judge whether the two values are the same.
If any of the following is true, the two values are the same:

Both values are undefined
Both values are null
Both values are true or false
Two values are strings of the same number of characters in the same order.
Two values point to the same object
Both values are numbers and
Are all positive zeros +0
Are all negative zero -0
Nans
Are all the same numbers except zero sum and NaN

Object.is('foo', 'foo');  // true
 Object.is(window, window);  // true
 
 Object.is('foo', 'bar');  // false
 Object.is([], []);  // false
 
 var test = { a: 1 };
 Object.is(test, test);  // true
 
 Object.is(null, null);  // true
 
 //Special case
 Object.is(0, -0);  // false
 Object.is(-0, -0);  // true
 Object.is(NaN, 0/0);  // true

Object.freeze()

Freezing an object means that new attributes cannot be added to the object, the values of its existing attributes cannot be modified, the existing attributes cannot be deleted, and the enumeratability, configurability, and writeability of the existing attributes of the object cannot be modified. In other words, this object is always immutable. This method returns the frozen object.

var obj = {
 prop: function() {},
 foo: 'bar'
 };
 
 //New attributes will be added. Existing attributes may
 //will be modified or removed
 obj.foo = 'baz';
 obj.lumpy = 'woof';
 delete obj.prop;
 
 //Objects passed as parameters and returned objects are frozen
 //So there is no need to save the returned object (because the two objects are congruent)
 var o = Object.freeze(obj);
 
 o === obj;  // true
 Object.isFrozen(obj);  // === true
 
 //Now any changes will be invalid.
 obj.foo = 'quux';  //Do nothing silently
 //Do not add this attribute silently
 obj.quaxxor = 'the friendly duck';
 console.log(obj)

Object.isFrozen()
Judge whether an object is frozen.


Object.preventExtensions()
Object cannot add new attributes. You can modify or delete existing attributes and cannot add new attributes.


var obj = {
 name :'lilei',
 age : 30 ,
 sex : 'male'
 }
 
 obj = Object.preventExtensions(obj);
 console.log(obj);  // {name: "lilei", age: 30, sex: "male"}
 obj.name = 'haha';
 console.log(obj)     // {name: "haha", age: 30, sex: "male"}
 delete obj.sex ;
 console.log(obj);  // {name: "haha", age: 30}
 obj.address  = 'china';
 console.log(obj)     // {name: "haha", age: 30}

Object.isExtensible()

Judging whether an object is extensible, Object.preventExtensions, Object.seal or Object.freeze methods can all mark an object as non-extensible.


Object.seal()

The Object.seal () method can seal an object and return the sealed object. Sealing an object will make the object unable to add new attributes, and all existing attributes will become unconfigurable. The effect of non-configurable attribute is that the attribute cannot be deleted, and a data attribute cannot be redefined as an accessor attribute, or vice versa. However, the value of the property can still be modified. An attempt to delete the attribute of a sealed object or convert the attribute of a sealed object from a data attribute to an accessor attribute will result in a silent failure or throw a TypeError exception. Attributes inherited from the prototype chain will not be affected. But ..protoThe value of the () attribute cannot be modified.

var obj = {
 prop: function () {},
 foo: "bar"
 };
 
 //New attributes can be added, and the values of existing attributes can be modified or deleted.
 obj.foo = "baz";
 obj.lumpy = "woof";
 delete obj.prop;
 
 var o = Object.seal(obj);
 
 assert(o === obj);
 assert(Object.isSealed(obj) === true);
 
 //You can still modify the value of the attribute on the sealed object.
 obj.foo = "quux";
 
 //But you cannot redefine a data attribute as an accessor attribute.
 Object.defineProperty(obj, "foo", { get: function() { return "g";   } });  //Throws TypeError Exception
 
 //Now, any modification other than attribute values will fail.
 obj.quaxxor = "the friendly duck";  //Silence failed, new attribute was not added successfully
 delete obj.foo;  //Silence failed, attribute not deleted successfully
 
 //... In strict mode, a TypeError exception is thrown
 function fail() {
 "use strict";
 delete obj.foo;  //Throws TypeError Exception
 obj.sparky = "arf";  //Throws TypeError Exception
 }
 fail();
 
 //using the Object.defineProperty method also throws an exception.
 Object.defineProperty(obj, "ohai", { value: 17 });  //Throws TypeError Exception
 Object.defineProperty(obj, "foo", { value: "eit" });  //Successfully changed the original value

Object.isSealed()
Judging whether an object is sealed or not