Object Related methods in an Object
Object Native methods of objects fall into two categories: methods of Object itself and methods of Object instances.
Methods are defined directly on the current constructor Object, also known as static methods
/ / example Object. XXX ()Copy the code
Object instance methods are the methods defined in Object.prototype. It can be shared directly by Object instances
Object.prototype.hello = function(){ console.log('hello'); } var obj = new Object(); obj.hello(); //helloCopy the code
Static methods of Object
Static methods are methods specified in the Object itself
Object.keys()
Keys (), which gets the property name, is used to traverse the property of the object. You can pass an argument that is an object and return an array of all the property names of the object itself.
Var arr = "1", "2", "3", "4"]. The console log (Object. The keys (arr)) / / get the keys of the arrayCopy the code
Var obj={1:"w", 4:"c", 3:"d"} console.log(object.keys (obj)) // Get the array from small to largeCopy the code
Obj.getOwnPropertyNames()
The keys method takes a parameter and returns an array containing all the properties of the object. Object. The getOwnPropertyNames method and the Object. The keys are similar, is also accept an Object as a parameter, returns an array that contains all of the attributes of the Object itself.
var obj={
1:"w",
4:"c",
5:"d"
}
console.log(Object.getOwnPropertyNames(obj))
Copy the code
For ordinary objects,Object.keys()
andObject.getOwnPropertyNames()
The result is the same. The only difference is when non-enumerable properties are involved.Object.keys
Method returns only enumerable properties,Object.getOwnPropertyNames
Method also returns an attribute name that is not enumerable.
Enumeration: can be understood as whether a property can be traversed, traversable is called enumerable property, not traversable is called not enumerable property
var arr=["a","b","c","d"]
console.log(Object.getOwnPropertyNames(arr))
Copy the code
In the code above, the arraylength
Properties are non-enumerable properties, so they only appear inObject.getOwnPropertyNames
Method.
Since JavaScript does not provide a way to count the number of attributes on an object, you can use these two methods instead.
Var obj = {0: 'a', 1: 'b', 2: 'c'} Object. The keys (obj). Length / / 3 Object. GetOwnPropertyNames (obj). Length / / 3Copy the code
In general, the Object. Keys method is the most popular way to traverse an Object’s properties.
Object.getPrototypeOf()
Object.getprototypeof method that takes the Object and returns the prototype of the Object. This is the standard way to get a prototype object
function fn(){};
var f1=new fn();
console.log(Object.getPrototypeOf(f1))
console.log(Object.getPrototypeOf(f1)=== fn.prototype)
Copy the code
This method knows that the prototype of the object instance F1 is fn’s prototype.
We have some special prototypes at this time:
GetPrototypeOf ({}) === object. prototype // true // Object.prototype is null Function. Prototype Function f() {} Object.getPrototypeOf(f) === Function.prototype // trueCopy the code
Object.setPrototypeOf()
This method takes two arguments, the first an existing object and the second a prototype object.
var a = {}; var b = {x : 1}; Object.setPrototypeOf(a,b); console.log(Object.getPrototypeOf(a)); //{x:1}Copy the code
The new command can be emulated using the object. setPrototypeOf method.
var F = function () { this.foo = 'bar'; }; var f = new F(); Console. log(f) // equivalent to var f = object.setProtoTypeof ({}, f.prototype); F.call(f); console.log(f)Copy the code
Object.create()
A common way to generate instance objects is to make the constructor return an instance using the new command. But a lot of times, you can only get one instance object, it might not be generated by the constructor at all, so can you generate another instance object from one instance object?
JavaScript provides the object.create method to fulfill this requirement. The method takes an object as an argument and returns an instance object based on it. This instance fully inherits the properties of the prototype object.
Var A = {hello: function () {console.log('hello'); }}; Var B = object.create (A); console.log(Object.getPrototypeOf(B) === A )// true B.hello() // hello console.log(B.hello === A.hello )// trueCopy the code
B
Object throughObject.create
To generate andB
Inheritance alsoA
(var B = Object.create(A);
) theA
Object as aB
The prototype returns a new instance throughObject.getPrototypeOf(B)
To obtainB
Is the prototype ofA
.B
andA
There arehello
This method,B
You can callhello
This method.
If you prototype B from object A, then B can inherit from object A. In addition to the two methods mentioned above,Object has a number of other static methods, which we’ll cover in more detail later
Other methods
1. Methods related to object attribute model
Object. GetOwnPropertyDescriptor () : get a property description of objects. Object.defineproperty () : Defines a property by describing an Object. Object.defineproperties () : Define multiple properties by describing objects.
2. Methods of controlling object state (Understanding section)
Object.preventextensions () : Prevents Object expansion. Object.isextensible () : determines whether an Object isExtensible. Object.seal() : disables Object configuration. Object.issealed () : Determines whether an Object is configurable. Object.freeze() : Freezes an Object. Object.isfrozen () : checks whether an Object isFrozen.
Object instance method
Methods are defined on object.prototype objects. We call them instance methods, and all instance objects of Object inherit these methods
Object Instance Object methods, there are six main.
- Object.prototype.valueof () : returns the valueOf the current Object.
- Object. The prototype. The toString () : returns the current Object corresponding to a string.
- Object. The prototype. ToLocaleString () : returns the current Object corresponding to the local string.
- Object. The prototype. The hasOwnProperty () : whether a property for the current of the attributes of the Object itself is inherited from the prototype Object’s properties.
- Object. The prototype. IsPrototypeOf () : whether the current Object to another Object of the prototype.
- Object. The prototype. PropertyIsEnumerable () : to judge whether a property can be enumerated.
Object. The prototype. The valueOf () :
Returns the value of the current object. The default is to return the object itself.
var obj = new Object(); obj.valueOf() === obj; //trueCopy the code
use
This method can be used by default for automatic type conversions
var obj = new Object(); // by default, JavaScript calls valueOf(), evaluates the valueOf obj and adds it to 1. Console.log (1+obj); //"1[object Object]"Copy the code
So, if you customize the valueOf method, you can get the result you want
So let’s say I call 1+obj and I want it to be equal to 3. ValueOf (obj.valueOf) with obj. Rewrite this function to return a 2. Obj +1 will implicitly call valueOf to get the desired result
var obj = new Object(); Obj. valueOf = function(){return 2; } console.log(1 + obj); Obj implicitly calls valueOf, where valueOf is 2Copy the code
With definedObject.valueOf
coverObject.prototype.valueOf
ValueOf = obj; valueOf = obJ; valueOf = obJ; valueOf = obJ;
Object.prototype.toString()
Returns the string representation of the current object. The default is to return the type of string.
var obj1 = new Object(); console.log(obj1.toString()); //"[object Object]" var obj2 = {a:1}; obj2.toString() // "[object Object]"Copy the code
The result returned indicates the type of the object.
Object object by itself is not very useful, but by customizing the toString method, you can make an object get the desired string form when the automatic type conversion is performed.
var obj = new Object(); obj.toString = function(){ return 'hello'; } console.log(obj + '' + 'world'); //"hello world"Copy the code
Things like arrays, strings, functions,Date
Each object has its own custom definedtoString
Method, coveredObject.prototype.toString()
methods
console.log([1, 2, 3].toString() ); / / "1, 2, 3" is the console. The log (' 123 '. The toString ()); // "123" console.log((function(){ return 123 }).toString()); console.log((new Date()).toString())Copy the code
Object.prototype.toLocaleString()
Returns the local string representation of the current object. The toString method is the same as the toString method.
Currently, there are three main objects that have custom toLocaleString methods
Array. The prototype. ToLocaleString () Number. The prototype. ToLocaleString () the Date. The prototype. ToLocaleString (), for instance, The toString and toLocaleString returns for instances of dates are different, and toLocaleString returns depend on the locale specified by the user
var date = new Date();
console.log(date.toString()) // "Tue Jan 01 2018 12:01:33 GMT+0800 (CST)"
console.log(date.toLocaleString()) // "1/01/2018, 12:01:33 PM"
Copy the code
toString
It is international and unified.toLocaleString
Is to return our corresponding results based on the location
Object.prototype.isPrototypeOf()
Used to determine whether the object is a prototype of another object
var o1 = {}; var o2 = Object.create(o1); var o3 = Object.create(o2); console.log(o2.isPrototypeOf(o3)); //true console.log(o1.isPrototypeOf(o3)); //trueCopy the code
In the code above,o1
ando2
Are allo3
The prototype. This means that as long as the instance object is on the prototype chain of the parameter object,isPrototypeOf
Methods all returntrue
.
/ / Object. If the prototype for the Object prototype of the console, log (Object. The prototype. IsPrototypeOf ({})); / / true / / Object. The prototype for an array of prototype console. The log (Object. The prototype. IsPrototypeOf ([])); / / true / / Object. The prototype is null prototype of the console, log (Object. The prototype. IsPrototypeOf (Object. The create (null))); // falseCopy the code
把null
As a prototype,object
It’s just one layer abovenull
That’s the top layer. Then of course it isn’tObject.prototype
. So backfalse
. And as you can see from this example,Object.prototype
Is the top of the prototype chain, so various instances like arrays and objects are returnedtrue
. Only direct inheritancenull
Except for this object, because it’s notobject.prototype
The prototype of the
Every instance object has a __proto__ inside it. In the same way that object.prototype is an instance object, there is also a __proto__ inside it, which also points to its prototype object.
console.log(Object.prototype.__proto__); // null
Copy the code
Object. Prototype points to null as an instance prototype
Object.prototype.hasOwnProperty()
Check if the current instance object has its own property, return true if it does, false if it does not.
var obj = { a: 123 } console.log(obj.hasOwnProperty('b')); //false console.log(obj.hasOwnProperty('a')); //trueCopy the code
We know thatobj
The instance object inheritsObject
Properties on the prototype, such as passObject
calltoString()
.toString()
Returns as an inherited propertyfalse
.
var obj = { a: 123 } console.log(obj.hasOwnProperty('toString')); //false determines whether there is a toString attributeCopy the code
Object. The prototype. The hasOwnProperty method accepts a string as an argument and returns a Boolean value that indicates that the instance whether Object itself has the attribute. Only the instance’s own properties are checked, and the inherited properties return false.
Attribute description object
JavaScript provides an internal data structure that describes the properties of an object and controls its behavior, such as whether the property is writable, traversable, and so on. This internal data structure is called an attribute description object. Each attribute has its own attribute description object, which stores some meta information about the attribute
var obj={}; Obj. name=" little sun "; Name =" obj "; // Name is console.log(obj.propertyIsEnumerable("name")) which can be modified; // Enumerable can be traversed console.log(obj.name); // Print console.log(delete obj.name); // Can be deletedCopy the code
Enumerable: true, // Enumerable: true // The default value of the specified function is undefined, and the default value of the specified function is undefined}Copy the code
The property description object provides six meta-properties
| attributes meaning | | | — — — — — — — — — — — — — — — – | — — — — — — — — — — — — — — — – | — — — — — — — — — — — — — — — – | | value | value is the attribute of the attribute value, the default value is undefined. | | writable | writable is a Boolean value that indicates whether the attribute value (value) can be changed (i.e., whether can write), the default is true. | | enumerable | enumerable is a Boolean value, according to whether the attribute can traverse, the default is true. If set to false, certain operations (such as for… In loop, object.keys ()) skips this property. | | configurable | configurable is a Boolean value, said configurability, the default is true. If set to false, this prevents operations from overwriting the property, such as not being able to delete the property or change the property description object (except the value property) for the property. That is, the writability of the attribute description object is controlled by a different property. | | get | get is a function, representing the properties of value function (getter), the default value is undefined. | | set | set is a function, according to the properties of value function (setter), the default value is undefined. |
In a description object, the behavior of its internal control properties is controlled by these properties.
By * * Object. GetOwnPropertyDescriptor () method to get the * * these attributes.
Object.getOwnPropertyDescriptor()
Object. GetOwnPropertyDescriptor () method can obtain property description Object. Its first argument is the target object, and its second argument is a string corresponding to the name of an attribute of the target object.
Object Examples:
var obj={}; Obj. name=" little sun "; Name =" obj "; / / the name of the console can be modified. The log (Object. GetOwnPropertyDescriptor (obj, "name")) / / retrieve attributes describe the configuration of the ObjectCopy the code
For example an array:
var arr=["1","2","3"]; arr.length=5; / / length can be written, here to write 5 console. The log (arr. Length) console. The log (Object. GetOwnPropertyDescriptor (arr, "0")); console.log(Object.getOwnPropertyDescriptor(arr,"length")); The console. The log (Object. GetOwnPropertyDescriptor (arr, "toString")) / / should not be used to inherited attributesCopy the code
Note:Object.getOwnPropertyDescriptor()
Methods can only be used on properties of the object itself, not inherited properties
Object.prototype.propertyIsEnumerable()
Check whether a property is enumerable. Enumerability is the property that can be traversed (the property of the instance itself), and non-enumerability is the property that cannot be traversed (inherited, set non-enumerable property).
var obj={}; obj.a=123; For (var key in obj){console.log(key) //a console.log(obj[key]) // print value} var obj={}; obj.a=123; The console. The log (Object. PropertyIsEnumerable (" a ")) / / a can be enumerated the console. The log (Object. PropertyIsEnumerable "toString ()) //toString is inherited and cannot be enumeratedCopy the code
Object.defineProperty()
The Object.defineProperty method allows you to describe an Object by attribute, define or modify an attribute, and then return the modified Object.
The syntax is as follows:
Object.defineproperty (Object, propertyName, attributesObject) //Object.defineProperty(The Object where the attribute belongs, the name of the attribute to be modified, the attribute description Object)Copy the code
Object.defineProperty
The method takes three arguments, as follows.
The name of the | meaning |
---|---|
object | The object of the property |
propertyName | A string representing the name of the property |
attributesObjec | Attribute description object |
` ` ` | |
var obj = Object.defineProperty({},’name’,{ |
Value :' 64x ', Writable :false, Enumerable :true, different :falseCopy the code
}) console.log(obj.name); // obj. Name = ‘obj ‘; console.log(obj.name); // delete obj.name; console.log(obj.name); // The sun can still be retrieved without being deleted
! [](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cb159c83ed0440799d115e5883ba1140~tplv-k3u1fbpfcp-zoom-1.image) In the code above, the 'object.defineProperty ()' method defines the 'obj.name' property. Because the property description object's 'writable' property is' false ', the 'obj.name' property is not writable. Notice that the first argument to the 'object.defineProperty' method here is' {} (a new empty Object) '. The 'name' attribute is defined directly on the empty Object and then returns the Object. This is the common use of 'Object.defineProperty()'. If the attribute already exists, the 'object.defineProperty ()' method is equivalent to updating the attribute description Object for the attribute. #### object.defineproperties () If multiple attributes are defined or modified at once, the 'object.defineproperties ()' method can be usedCopy the code
var obj = Object.defineProperties({}, { p1: { value: 123, enumerable: true }, p2: { value: ‘abc’, enumerable: }, x: {get: function () {this.p1 + this.p2}, Enumerable :true, different :true}}); console.log(obj.p1); //123 console.log(obj.p2); //”abc” console.log(obj.p3); //”123abc”
! [](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/150c0938e92f40a0ba4013ed8bcf3221~tplv-k3u1fbpfcp-zoom-1.image) In the above code, 'object.defineProperties ()' simultaneously defines three attributes of the 'obj' Object. When 'obj.p3' is called, each property description object has a 'get' and 'set' value function. 'GET' is used to fetch values of 'p1' and 'p2'. 'p3' defines the value function 'get', which is called each time the property is read. ** ** can't define writable as true. Try not to write **. If you define the function get (or set), you cannot set writable to trueCopy the code
var obj2=Object.defineProperty({},”name”,{ writable:true, get:function(){ return 456 } })
! [](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b68373f86d6249f68831f27196cf8662~tplv-k3u1fbpfcp-zoom-1.image) If ** defines the get function, it cannot also define the value attribute **Copy the code
var obj2=Object.defineProperty({},”name”,{ value:”123″, get:function(){ return 456 } })
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b446365d544f4ec195a64de6be2d52c9~tplv-k3u1fbpfcp-zoom-1.image) Attribute description objects in 'object.defineProperty ()' and 'object.defineProperties ()' arguments, The default value of 'writable', 'signals' and' enumerable 'is false.Copy the code
var obj = {}; Object.defineProperty(obj, ‘foo’, {}); Object.getOwnPropertyDescriptor(obj, ‘foo’) /* { configurable: false, enumerable: false, value: undefined, writable: false, } */
In the code above, 'obj.foo' is defined with an empty attribute description object, so you can see the default values for each meta-attribute. Obj doesn't work either. ### meta attribute #### value 'value' attribute is the value of the target attributeCopy the code
var obj = {}; obj.p = 123; console.log(Object.getOwnPropertyDescriptor(obj, ‘p’).value); //123 console.log(Object.defineProperty(obj, ‘p’, { value: 246 })); console.log(obj.p )// 246
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d78063ef20524fc7af2ce36a36f22c36~tplv-k3u1fbpfcp-zoom-1.image) The above code is an example of reading or overwriting 'obj. P' via the 'value' attribute. #### writable 'writable' property is a Boolean value that determines whether the value of the target property can be changed.Copy the code
var obj = {}; Object.defineproperty (obj, ‘a’, {value: 37, writable: false // cannot be modified}); console.log(obj.a )// 37 obj.a = 25; Console. log(obj.a)// 37
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bb768cf287e14afba9898766a5b9a504~tplv-k3u1fbpfcp-zoom-1.image) In the code above, the 'writable' property of 'obj. A' is' false '. Then, changing the value of 'obj. A' will have no effect. Note that in normal mode, assigning to a property whose 'writable' is' false 'does not report an error, but silently fails. However, an error is reported in strict mode, even if the 'A' attribute is reassigned to the same value.Copy the code
‘use strict’; var obj = {}; Object.defineProperty(obj, ‘a’, { value: 37, writable: false }); obj.a = 37;
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bfeb440dabeb4361a8965d6a388e0df9~tplv-k3u1fbpfcp-zoom-1.image) The code above is in strict mode and will report an error for any assignment to 'obj. A'. If the writable of an attribute of the prototype object is false, the child object will not be able to customize that attribute.Copy the code
var proto = Object.defineProperty({}, ‘foo’, { value: ‘a’, writable: false }); var obj = Object.create(proto); obj.foo = ‘b’; Console. log(obj.foo) // ‘a’
In the code above, 'proto' is a prototype object whose 'foo' property is unwritable. 'obj' objects inherit from 'proto' and can no longer customize this property. In strict mode, doing so also throws an error. One way around this limitation, however, is to override the attribute description object. The reason is that in this case, the prototype chain is completely ignored.Copy the code
var proto = Object.defineProperty({}, ‘foo’, { value: ‘a’, writable: false }); var obj = Object.create(proto); Object.defineProperty(obj, ‘foo’, { value: ‘b’ }); console.log(obj.foo) // “b”
#### enumerable 'Enumerable' returns a Boolean value indicating whether the target property is traversable or not. If an attribute's 'enumerable' is' false ', the following operations do not retrieve it - 'for... In 'loop -' object. key 'method -' json. stringify 'methodCopy the code
var obj = {}; Object.defineProperty(obj, ‘x’, { value: 123, enumerable: false }); obj.x // 123 for (var key in obj) { console.log(key); [] console.log(json.stringify (obj)) // “{}”
! [](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5338d765dbcb4f0c9ce096927e037927~tplv-k3u1fbpfcp-zoom-1.image) In the code above, the 'enumerable' of the 'obj.x' property is' false ', so no normal traversal can retrieve it, making it a bit like a 'secret' property, but not really private. You can still retrieve its value directly. Note that ` for... The 'in' loop includes inherited properties, and the 'object. keys' method does not. If you need to get all the attributes of the Object itself, whether can traverse, can use ` Object. GetOwnPropertyNames ` method.Copy the code
Function A(){this.name=”小 sun “; } function B(){ A.call(this); } var b=new B(); Object.defineproperty (b,”age”,{value:18, Enumrable :false // Non-enumerable attributes}) console.log(b); / / for… In traversing the inherited attributes can be traversed out for (var key in b) {the console. The log (key)} the console. The log (Object. GetOwnPropertyNames (b)) console.log(Object.keys(b))
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b2c35c42f1784d4491fa4b92771f4d1c~tplv-k3u1fbpfcp-zoom-1.image) Through ` for.. In ` cycle can not traverse enumerated attribute, ` Object. The keys (b) ` cannot obtain an enumerated attribute ` age `, but by ` Object. GetOwnPropertyNames ` properties of inheritance and an enumeration can be gained. In addition, the 'json.stringify' method rules out properties that 'Enumerable is false', which can sometimes be used to its advantage. You can set enumerable to false if your object's 'JSON' output excludes certain attributes. ####, signals' configurable ', returns a Boolean value that determines whether or not the property description object can be modified. The 'value', 'writable', 'Enumerable' and '64x' cannot be modified without any additional control system.Copy the code
var obj = Object.defineProperty({}, ‘p’, { value: 1, writable: false, enumerable: false, configurable: False // cannot be modified}); Object.defineProperty(obj, ‘p’, {value: 2}) // TypeError: Cannot redefine property: p
Object.defineProperty(obj, ‘p’, {writable: true}) // TypeError: Cannot redefine property: p
Object.defineProperty(obj, ‘p’, {enumerable: true}) // TypeError: Cannot redefine property: p
Object.defineProperty(obj, ‘p’, {configurable: true}) // TypeError: Cannot redefine property: p
In the code above, the '64x' of 'obj. P' is set to 'false'. Changes to 'value', 'writable', 'enumerable' and '64x' are different. Note that 'writable' only returns an error if 'false' is changed to 'true', which is allowed if 'true' is changed to 'false'Copy the code
var obj = Object.defineProperty({}, ‘p’, { writable: true, configurable: false }); console.log(Object.defineProperty(obj, ‘p’, {writable: false})); // The modification succeeded
As for 'value', any changes are allowed if either 'writable' and '64x' is set to 'true'.Copy the code
var o1 = Object.defineProperty({}, ‘p’, { value: 1, writable: true, configurable: false }); Object.defineproperty (o1, ‘p’, {value: 2}) // Changed successfully console.log(o1);
var o2 = Object.defineProperty({}, ‘p’, { value: 1, writable: false, configurable: true }); Object.defineProperty(o2, ‘p’, {value: 5}) console.log(o2);
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/af3a3446145743d392a9697019fb5c5d~tplv-k3u1fbpfcp-zoom-1.image) Configurability determines whether a target attribute can be deleted (delete).Copy the code
var obj = Object.defineProperties({}, { p1: { value: 1, configurable: true }, p2: { value: 2, configurable: false } }); delete obj.p1 // true delete obj.p2 // false obj.p1 // undefined obj.p2 // 2
Object defineProperty() stores the different attributes of the Object. DefineProperty (), which runs without any different information, is configured with '64x' and works without any additional information. Many advanced applications use this method >1. In addition to being defined directly, attributes can also be defined using accessors. The store function, called setter, uses properties to describe the set property of the object. The value function is called a getter, and uses the property to describe the object's get property >2. Once an accessor is defined for a target property, the corresponding function is executed whenever it is accessed. With this feature, you can implement many advanced features, such as a property that disables assignmentCopy the code
var obj = Object.defineProperty({},’p’,{ get:function(){ return ‘getter’; }, set:function(value){ console.log(‘setter:’+value); //”setter:123″ } }) console.log(obj.p )//”getter” obj.p = 123 ;
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/766bcb817e2b4b428d96636d9ea6f543~tplv-k3u1fbpfcp-zoom-1.image) In the code above, 'obj.p' defines the 'get' and 'set' attributes. 'get' is called when 'obj.p' is evaluated, and 'set' is called when assigning. This way we can set whether a property in an object can be assignedCopy the code
var obj = Object.defineProperty({},’p’,{ get:function(){ return ‘getter’; }, set:function(value){ // console.log(‘setter:’+value); //”setter:123″ return; } }) console.log(obj.p )//”getter” obj.p = 123 ;
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f5157eb4e6054cf09fec98e64ee9b3c8~tplv-k3u1fbpfcp-zoom-1.image) The 'set' code in the above code does not execute, so the assignment 'obj.p=123' below is unsuccessful. In addition to writing the code described above, JavaScript provides an easy way to write it. Get is a value function that cannot accept arguments. Set is a value function that can accept only one argument.Copy the code
Var obj={get p(){return “getter”; Console. log(“setter:”+value)}} console.log(obj.p); obj.p=123;
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/370731ccf5e44a91bb73bfa82f580c81~tplv-k3u1fbpfcp-zoom-1.image) Storage 'get' and 'set' are often used for attribute value dependencies, where an attribute has a 'value' attribute value, in which an operation is performed on an attribute value in the current object. Accessors are used when the value of a property depends on the internal data of the objectCopy the code
var obj = { n : 5, get next(){ return this.n++; }, set next(value){ if(value >= this.n){ this.n = value; }else{throw new Error(‘ New value must be greater than current value ‘); }}}; console.log(obj.next) //5 obj.next = 10; console.log(obj.next) //10 obj.next = 5; Console. log(obj.next) //10 // Uncaught Error: The new value must be greater than the current value
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/15c1c5f908504096adfa8c8407ceb546~tplv-k3u1fbpfcp-zoom-1.image) $n = $n; $n = $n; $n = $n; $n = $n; $n = $n; To review the data types in JavaScript, there are two types of data types: basic data types and reference data types. ** Basic data types: pass by value ** Classic examples:Copy the code
var a=1; var b=a; b=200; console.log(a); console.log(b);
! The [] (https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/48c2326fb00c44d39a3aa0f4f8c55220~tplv-k3u1fbpfcp-zoom-1.image), The value of 'b' is changed to 200. Changing the value of the variable after the copy does not affect the data in the original data type. This scheme is called deep copy. ** Reference data types: Reference types are passed by reference ** Examples:Copy the code
Var arr = [1, 2, 3, 4]; var newArr=arr; newArr.push(10); console.log(newArr); console.log(arr)
! [](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b675bd097d2f460ead24913597c231ec~tplv-k3u1fbpfcp-zoom-1.image) When the variable copies the data in the later object, the data in the original object also changes. This scheme is called shallow copy. > < span style = "max-width: 100%; clear: both; min-height: 1em; # # # shallow copyCopy the code
Var obj={name:”小 sun “, age:18, hobby:” 小 sun “, friend:{name:”小 孩 “, age:18, hobby:” 小 孩 “, friend:{name:”小 孩 “, Age :15}} function shadowCopy(toObject,fromObj){for(var key in fromObj){toObject[key]=fromObj[key]} return toObject; } var newObj = shadowCopy({},obj); Console. log(newObj) // Now the original object has been copied // Change the age of the new object newobj. age=20; NewObj. Friend. Name = “Ming”; console.log(newObj); console.log(obj)
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bd9f7c07cb5a4bb28958e2a4b2eb021b~tplv-k3u1fbpfcp-zoom-1.image) 'name' and 'age' are both basic data types. Now copy the data in 'obj' to the new object, copy each property in 'obj' directly to the new data, and make a custom function 'shadowCopy', passing in two parameters. The first argument 'toObject' and the second argument 'fromObj'. Copy from 'fromObj' to 'toObject'. Calling 'ShadowCopy' passes in an empty object, passes in the 'obj' object, and then 'returns' a copied object. 'var newObj' is a new object stored after the copy. 'ShadowCopy' returns the copied object 'return toObj' inside the ShadowCopy function. 'friend' is an object of reference type. If you want to implement a shallow copy, once 'newObj' should change the 'name' in 'friend'. Through ` for.. In 'loop inside' toObj[key]=fromObj[key] 'directly copied. Age is changed in newObj, but not in the original object obj. Because these are basic data types. But the 'name' in 'friend' changes both in the new object and the original object, because 'friend' is a reference type. Ann refers to the address to pass, change the new data address and change the original data address. > < p style = "max-width: 100%; clear: both; min-height: 1em; The shallow-copy copy only copies the attributes of the first layer and does not recursively copy all the values back (only attributes like name in obj, but friend copies a memory address). Recursion occurs when you iterate layer by layer. A deep copy is a full copy of the target, unlike a shallow copy that copies only one layer of references. As long as a deep copy is made, the original object and the current object are independent, no one affects who.Copy the code
Var obj = {name: “little”, the age: 18, hobby: [” play “, “running”], friend: {name: “little fatty”, the age: 15, friend: {name: “little color”, Age :12}}} function deepCopy(to,fromA){ For (var key in fromA){if(froma.hasownProperty (key)){// If (froma.hasownProperty (key)){// If (froma.hasownProperty (key)){ If (fromA[key] && typeof fromA[key] === “object”){//fromA[key] is an object and has a value. //fromA[key] constructor is an Array. To [key]=fromA[key]. Constructor ===Array? [] : {}; // deepCopy(to.[key],fromA[key]); // To [key] = = deepCopy(to[key],fromA[key]);
}else{fromA[key] =fromA[key]}} return to;Copy the code
} var newObj = deepCopy({},obj); NewObj. Friend. Name = “Ming”; Log (newObj) console.log(obj) console.log(obj) console.log(obj) console.log(obj
! [](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/dd975b1fc44f4b34be7a8374cc81fe2d~tplv-k3u1fbpfcp-zoom-1.image) ** Original data has not been changed, new data has been changed. The 'hasOwnProperty' property is used to filter out inherited properties. **Copy the code