Object.keys
- Returns an array of strings consisting of the self-enumerable properties of a given object
- The order of the attribute names in the array and the use of for… The in loop returns the same order as it iterates through the object.
- If the key-value of an object is not enumerable, an array of keys is returned.
var arr = ['a', 'b', 'c']; console.log(Object.keys(arr)); // console: ['0', '1', '2'] var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.keys(obj)); // console: ['0', '1', '2'] var anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(anObj)); // console: ['2', '7', '100'] var myObj = Object.create({}, { getFoo: { value: function () { return this.foo; }}}); myObj.foo = 1; console.log(Object.keys(myObj)); // console: ['foo'] In ES5, if the argument to this method is not an object (but a primitive value), it raises TypeError. In ES2015, non-object parameters are cast to an object. Object.keys("foo"); // TypeError: "foo" is not an object (ES5 code) Object.keys("foo"); / / / "0", "1", "2"]Copy the code
Object.defineProperty()
Object. DefineProperty (obj, prop, descriptor) :
-
Define a new property directly on an object, or modify an existing property of an object, and return the object.
Obj: Object on which attributes are to be defined. Prop: Name of the property to be defined or modified. Descriptor: Attribute descriptor to be defined or modifiedCopy the code
-
Return value: The object passed to the function.
-
Common attributes added through assignment operations are enumerable and can be rendered during attribute enumeration (for… In or object. keys methods), the values of these properties can be changed or deleted.
-
By default, attribute values added using Object.defineProperty() are not modifiable.
Example: First define an object
const obj = {
firstName: 'A',
lastName: 'B'
}
Copy the code
Add a fullName attribute to this object with the value obj.firstname – obj.lastname
Object.defineproperty (obj, 'fullName', {// Access descriptor // automatically called when reading this property value of the Object, This is obj get () {return this.firstName + '-' + this.lastName}, This is obj set (value) {const names = value.split('-') this.firstName = names[0] this.lastName = names[1]}}) console.log(obj.fullName) // A-BCopy the code
Attribute descriptor
- There are two main types of property descriptors that currently exist in objects: data descriptors and access descriptors.
- Data descriptor: is a property with a value that may or may not be writable.
- Access descriptors: Properties described by getter-setter functions.
- The descriptor must be one of these two forms; You can’t be both.
Both data descriptors and access descriptors have the following optional key values
configurable
: If and only if of this attributeconfigurable
为true
, the attribute descriptor can be changed, and the attribute can also be deleted from the corresponding object. The default isfalse
.enumerable
: If and only if of this attributeenumerable
为true
The property can appear in the enumeration properties of the object. The default isfalse
. The data descriptor also has the following optional key values:value
: Indicates the value of the property. It can be anything that worksJavaScript
Value (number, object, function, etc.) The default isundefined
.writable
: If and only if of this attributewritable
为true
When,value
Can be changed by the assignment operator. The default isfalse
.
The access descriptor also has the following optional key values:
get
: one is provided for the propertygetter
If notgetter
For theundefined
. When the property is accessed, the method is executed with no arguments passed in, but is passed inthis
Object (because of inheritance, herethis
Not necessarily the object that defines the property). The default isundefined
.set
: one is provided for the propertysetter
If notsetter
For theundefined
. This method is triggered when the property value is modified. This method takes a unique parameter, the new parameter value for the property. The default isundefined
.
Key values that the descriptor can have at the same time
- If a descriptor does not have
value,writable,get
和set
Any keyword, then it will be considered a data descriptor. - If a descriptor has both (
The value or writable
) and (Get or set
) keyword will generate an exception.
Create a properties
- If the specified property does not exist in the object,
Object.defineProperty()
Create this property. - When fields are omitted from the descriptor, those fields will use their default values.
- The default value for any field that has a Boolean value is
false
.value
.get
和set
The default value of the field isundefined
. - A no
get/set/value/writable
The defined property is said to be “generic” and is “keyed in” as a data descriptor
var o = {}; Object.defineproperty (o, "A ", {value: 37, writable: true, enumerable: true, configurable : true }); // Object O has property A, value 37 // Add an example of property and access descriptor to object var bValue; Object.defineProperty(o, "b", { get : function(){ return bValue; }, set : function(newValue){ bValue = newValue; }, enumerable : true, configurable : true }); o.b = 38; Object.defineproperty (o, "conflict", {value: 0x9f91102, get: function() { return 0xdeadbeef; }}); // throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptorsCopy the code
Modify the properties
- If the attribute already exists,
Object.defineProperty()
Attempts will be made to modify this property based on the value in the descriptor and the current configuration of the object. - If the old descriptor calls it
configurable
Property set tofalse
, the property is considered “unconfigurable” and no property can be changed (except by changing writable to false in one direction). - You cannot switch between data and accessor property types when the property is not configurable.
- When trying to change a non-configurable property (except
value
andwritable
Property is thrownTypeError
Unless the current value is the same as the new value. Writable
Properties: whenwritable
Property set tofalse
, the property is called unwritable. It cannot be redistributed.
As the example shows, trying to write a non-writable property does not change it, nor does it raise an error.
var o = {}; // Creates a new object Object.defineProperty(o, 'a', { value: 37, writable: false }); console.log(o.a); // 37 o.a = 25; Console. log(o.a); // No errors are reported, but changes do not take effect. // logs 37 // strict mode error (function() {'use strict'; var o = {}; Object.defineProperty(o, 'b', { value: 2, writable: false }); o.b = 3; // throws TypeError: "b" is read-only return o.b; // returns 2 without the line above }());Copy the code
Enumerable features
Enumerable defines whether an object’s property can be considered in a for… Are enumerated in the in loop and object.keys ().
var o = {}; Object.defineProperty(o, "a", { value : 1, enumerable:true }); Object.defineProperty(o, "b", { value : 2, enumerable:false }); Object.defineProperty(o, "c", { value : 3 }); // enumerable defaults to false o.d = 4; // Enumerable is true for (var I in o) {console.log(I); } // Print 'a' and 'd' (in undefined order) object.keys (o); // ["a", "d"] o.propertyIsEnumerable('a'); // true o.propertyIsEnumerable('b'); // false o.propertyIsEnumerable('c'); // falseCopy the code
Configurable features:
configurable
Properties indicate whether attributes of an object can be deleted and dividedvalu
E andwritable
Whether other features can be modified.- if
o.a
的configurable
Properties fortrue
, no errors are thrown, and the attribute is deleted at the end.
var o = {}
Object.defineProperty(o, 'a', {
get: function () {
return 1
},
configurable: false
})
Object.defineProperty(o, 'a', {configurable: true}) // throws a TypeError
Object.defineProperty(o, 'a', {enumerable: true}) // throws a TypeError
Object.defineProperty(o, 'a', {value: 12}) // throws a TypeError
Object.defineProperty(o, 'a', { // throws a TypeError (set was undefined previously)
set: function () {
}
})
Object.defineProperty(o, 'a', { // throws a TypeError (even though the new get does exactly the same thing)
get: function () {
return 1
}
})
console.log(o.a) // 1
delete o.a // false
console.log(o.a) // 1
Copy the code
Add multiple attributes and defaults: It is important to consider the default attribute values assigned to attributes. In general, attribute defaults in data descriptors are different when assigning attributes to objects using the dot operator and Object.defineProperty(), as shown in the following example.
var o = {}; o.a = 1; DefineProperty (o, "A ", {value: 1, writable: true, 64x: true, enumerable: true}); // Equal to: Object.defineProperty(o," A ", {value: 1, writable: true, different: true, enumerable: true}); // On the other hand, object.defineProperty (o, "a", {value: 1}); DefineProperty (o, "A ", {value: 1, writable: false, 64x: false, Enumerable: false}); // Equal to: Object.defineProperty(o," A ", {value: 1, writable: false, different: false, Enumerable: false});Copy the code
General Setters and Getters: The following example shows how to implement a self-archiving object. When the Temperature property is set, the Archive array retrieves the log entry.
function Archiver() { var temperature = null; var archive = []; Object.defineProperty(this, 'temperature', { get: function() { console.log('get! '); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); }}); this.getArchive = function() { return archive; }; } var arc = new Archiver(); arc.temperature; // 'get! ' arc.temperature = 11; arc.temperature = 13; arc.getArchive(); // [{val: 11}, {val: 13}] function () { return 'I alway return this string,whatever you have assigned'; }, set: function () { this.myname = 'this is my name string'; }}; function TestDefineSetAndGet() { Object.defineProperty(this, 'myproperty', pattern); } var instance = new TestDefineSetAndGet(); instance.myproperty = 'test'; console.log(instance.myproperty); // 'I alway return this string,whatever you have assigned' console.log(instance.myname); // 'this is my name string'Copy the code
Inherited attributes: If the visitor’s attributes are inherited, its GET and set methods are called when the child object’s attributes are accessed or modified. If these methods store a value in a variable, the value is shared by all objects.
function myclass() {
}
var value;
Object.defineProperty(myclass.prototype, "x", {
get() {
return value;
},
set(x) {
value = x;
}
});
var a = new myclass();
var b = new myclass();
a.x = 1;
console.log(b.x); // 1
Copy the code
This can be solved by storing the value in another attribute. In the GET and set methods, this refers to an object whose properties are being accessed and modified.
function myclass() { } Object.defineProperty(myclass.prototype, "x", { get() { return this.stored_x; }, set(x) { this.stored_x = x; }}); var a = new myclass(); var b = new myclass(); a.x = 1; console.log(b.x); // undefinedCopy the code
Unlike the visitor attribute, the value attribute is always set on the object itself, not a stereotype. However, if a non-writable property is inherited, it still prevents the object’s properties from being modified.
function myclass() { } myclass.prototype.x = 1; Object.defineProperty(myclass.prototype, "y", { writable: false, value: 1 }); var a = new myclass(); a.x = 2; console.log(a.x); // 2 console.log(myclass.prototype.x); // 1 a.y = 2; // Ignored, throws in strict mode console.log(a.y); // 1 console.log(myclass.prototype.y); / / 1Copy the code
Object.create
-
Create a new object, using an existing object to provide the __proto__ of the newly created object.
-
Syntax: Object.create(proto, propertiesObject)
Proto: The prototype object of the newly created object. PropertiesObject: Optional. If it is not specified as undefined, it is the property descriptor and corresponding property name of the object to be added to the newly created object for enumerable properties (that is, properties defined by itself, rather than enumerated properties in its stereotype chain). These properties correspond to the second argument to Object.defineProperties(). If the propertiesObject argument is null or a non-original wrapped object, a TypeError exception is thrown.Copy the code
-
Return value: a new object with the specified prototype object and properties.
-
1. Define a new empty object obj inside the method
-
2. Point the object of obj._proto__ to the passed parameter proto
-
3. Return a new object
Object.create() differs from new Object()
New Object()
var newObj = { name: 'fx', why: { day: 1 } } var b = new Object(newObj) b.name = 'bfx' b.why = { bday: Log ('newObj :', newObj) console.log('newObj :', newObj)Copy the code
The output is as follows
Object. Create ()
var newObj = { name: 'fx', why: { day: 1 } } var b = Object.create(newObj) console.log(b) b.name = 'bfx' b.why = { bday: Log ('newObj :', newObj) console.log('newObj :', newObj)Copy the code
The output is as follows
Ex. :
O = object.create ({}, {p: {value: 42}}) // The omitted property defaults to false, so p is not writable, enumerable, or configurable: o.p = 24 console.log(o.p) // 42 o.q = 12 for (var prop in o) { console.log(prop) } //"q" delete o.p // false delete o.q Po2 = Object. Create ({}, {p: {value: 42, writable: true, Enumerable: true, different: true } }); // Shape - Superclass function Shape() {this.x = 0; this.y = 0; Function (x, y) {this.x += x; // function(x, y) {this.x += x; this.y += y; console.info('Shape moved.'); }; // Rectangle - subclass (subclass) function Rectangle() {shape.call (this); Rectangle. Prototype = object.create (Shape. Prototype); // Rectangle. Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log('Is rect an instance of Rectangle? ', rect instanceof Rectangle); // true console.log('Is rect an instance of Shape? ', rect instanceof Shape); // true rect.move(1, 1); Outputs, 'Shape Moved.' If you want to inherit multiple objects, use mixin. function MyClass() { SuperClass.call(this); OtherSuperClass.call(this); Prototype = object.create (superclass.prototype); / / mixed other Object. The assign (MyClass. Prototype, OtherSuperClass. Prototype); / / to specify the constructor MyClass. Prototype. Constructor = MyClass; MyClass.prototype.myMethod = function() { // do a thing }; Object.assign copies functions from the OtherSuperClass prototype to the MyClass prototype, making all instances of MyClass available to OtherSuperClass methods. var o; // Create an empty Object with the prototype null o = object.create (null); o = {}; // An empty Object created literally is equivalent to: o = object.create (object.prototype); Foo: {writable:true, different :true, value: 64x: disables any additional information that works without any additional control. Bar: {64x: false, get: function() {return 10}, set: disables any additional information, disables any additional information, and disables any additional information. function(value) { console.log("Setting `o.bar` to", value); }}}); function Constructor(){} o = new Constructor(); O = object.create (Constructor. Prototype); Of course, if there is some initialization code in the Constructor function, object.create cannot execute that codeCopy the code
PropertyIsEnumerable propertyIsEnumerable
- Returns a Boolean value indicating whether the specified property is enumerable.
- grammar
obj.propertyIsEnumerable(prop)
- Each object has one
propertyIsEnumerable
Methods. This method determines whether a property specified in an object can befor... in
Loop enumeration, except for properties inherited through the stereotype chain. This method returns if the object has no specified propertiesfalse
.
Every object has a propertyIsEnumerable method. This method determines whether a property specified in an object can be for… The in loop enumerates, except for properties inherited through the stereotype chain. This method returns false if the object has no specified properties.
var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyIsEnumerable('prop'); // Return true A.pertyIsEnumerable (0); // Return true === var a = ['is enumerable']; a.propertyIsEnumerable(0); // Return true A.pertyIsEnumerable ('length'); / / returns false math.h propertyIsEnumerable (' random '); / / returns false enclosing propertyIsEnumerable (' Math '); / / returns falseCopy the code
Own properties and inherited properties
var a = []; a.propertyIsEnumerable('constructor'); // Return false function firstConstructor() {this.property = 'is not enumerable'; } firstConstructor.prototype.firstMethod = function() {}; function secondConstructor() { this.method = function method() { return 'is enumerable'; }; } secondConstructor.prototype = new firstConstructor; secondConstructor.prototype.constructor = secondConstructor; var o = new secondConstructor(); o.arbitraryProperty = 'is enumerable'; o.propertyIsEnumerable('arbitraryProperty'); // Return true o.pertyIsEnumerable ('method'); // Return true o.pertyIsEnumerable ('property'); // Return false. Perty = 'is enumerable'; o.propertyIsEnumerable('property'); // Returns true // These return false because propertyIsEnumerable is not considered in the prototype chain (although the last two can be looped in a for-in loop). o.propertyIsEnumerable('prototype'); // Return false (according to JS 1.8.1/FF3.6) o.pertyIsEnumerable ('constructor'); // Return false o.PertyIsEnumerable ('firstMethod'); / / returns falseCopy the code
hasOwnProperty
- Returns a Boolean indicating whether the object has the specified property in its own property (that is, whether it has the specified key).
obj.hasOwnProperty(prop)
prop
Of the property to be detectedString
A string representation of the name, orSymbol
.- All inherited
Object
Object is inherited tohasOwnProperty
Methods. This method can be used to detect whether an object has a specific property of itself; andin
Depending on the operator, this method ignores properties inherited from the stereotype chain.
HasOwnProperty returns true as long as the property exists, even if the property value is null or undefined.
o = new Object(); o.propOne = null; o.hasOwnProperty('propOne'); // return true. Proptwo = undefined; o.hasOwnProperty('propTwo'); / / return trueCopy the code
Self attributes and inherited attributes
o = new Object(); o.prop = 'exists'; o.hasOwnProperty('prop'); // Return true o.hasownProperty ('toString'); // Return false o.hasownProperty ('hasOwnProperty'); / / returns falseCopy the code
Iterate over all of an object’s own properties
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
console.log('this is fog (' +
name + ') for sure. Value: ' + buz[name]);
}
else {
console.log(name); // toString or something else
}
}
Copy the code
in
- If the specified property is in the specified object or its stereotype chain
in
Operator returntrue
. - prop in object
var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); 0 in trees // returns true 3 in trees // Returns true 6 in trees // Returns false "bay" in trees // Returns false (must use index number, not array element value) "length" In trees // returns true (length is an array property) "PI" in Math // Returns true "toString" in {}; / / return trueCopy the code
The right-hand operand of in must be an object value. For example, you can specify strings created using the String constructor, but not String literals.
var color1 = new String("green"); Var color2 = "coral"; "Length" in color2 error (color2 is not an object)Copy the code
Object.prototype.toString()
- Grammar:
obj.toString()
- Return value: a string representing the object.
- Each object has one
toString()
Method, automatically called when the object is represented as a text value, or when an object is referenced as an expected string - By default,
toString()
Methods are used by eachObject
Object inheritance. If this method is not overridden in the custom object,toString()
return"[object type]"
Where type is the type of the object. toString()
Call null to return[object Null]
.undefined
return[object Undefined]
var o = new Object();
o.toString(); // returns [object Object]
Copy the code
Detect object types using toString()
var toString = Object.prototype.toString; toString.call(new Date); // [object Date] toString.call(new String); // [object String] toString.call(Math); // [object Math] //Since JavaScript 1.8.5 tostring. call(undefined); // [object Undefined] toString.call(null); // [object Null]Copy the code