Object Object
Outline
JavaScript provides native Object
objects (note that the chapeau O
is capitalized), this chapter describes the various methods of the object native.
All other objects are inherited from JavaScript Object
objects, those objects are Object
instances.
Object
Native method object into two categories: Object
process itself and the Object
example method.
(1) Object
the object itself method
The so-called "own way" is defined directly in the Object
method of the object.
Object.print = function (o) { console.log(o) };
In the above code, print
the method is defined directly Object
on the object.
(2) Object
Examples of the method
Examples of the method is defined in a so-called Object
prototype object Object.prototype
methods on. It can be Object
used as examples.
Object.prototype.print = function () {
console.log(this);
};
var obj = new Object();
obj.print() // Object
The above code, Object.prototype
defines a print
method, and then generate a Object
example obj
. obj
Directly inherited Object.prototype
properties and methods can be used directly obj.print
invoke print
methods. In other words, obj
the object of the print
method is essentially calling Object.prototype.print
method.
About the prototype object of object.prototype
a detailed explanation, see "Object Oriented Programming" section. Here just know that it is defined in Object.prototype
the object properties and methods above, will be shared by all instances of the object can be.
The following describes the first Object
as a function of usage, and then introduce Object
the native object method, the object itself into (also known as "static method") and the example method of two parts.
Object()
Object
Itself is a function that can be used as tool method, any value into an object. This method is commonly used to ensure that a value must be the object.
If the argument is null (or as undefined
and null
), Object()
returns a null object.
var obj = Object();
// 等同于
var obj = Object(undefined);
var obj = Object(null);
obj instanceof Object // true
The meaning of the above code, is undefined
and null
converted to the object, the result of a null object obj
.
instanceof
Operator is used to verify whether a specified object is an instance constructor. obj instanceof Object
Return true
, it means obj
the object is Object
an instance.
If the parameter is a value of the original type, Object
a method which is converted to the corresponding object instance of the package (see "primitive type wrapper object" chapter).
var obj = Object(1);
obj instanceof Object // true
obj instanceof Number // true
var obj = Object('foo');
obj instanceof Object // true
obj instanceof String // true
var obj = Object(true);
obj instanceof Object // true
obj instanceof Boolean // true
In the above code, Object
the parameter values of various functions are primitive types, the object is converted into a primitive type value corresponding to the object to be wrapped.
If the Object
method parameter is an object, it always returns the object that is not converted.
var arr = [];
var obj = Object(arr); // 返回原数组
obj === arr // true
var value = {};
var obj = Object(value) // 返回原对象
obj === value // true
var fn = function () {};
var obj = Object(fn); // 返回原函数
obj === fn // true
Using this, you can write a function to determine whether a variable object.
function isObject(value) {
return value === Object(value);
}
isObject([]) // true
isObject(true) // false
Object constructor
Object
Not only can function as a tool to use, you can also use as a constructor, which can be used in front of new
the command.
Object
The primary use of a constructor, a new object is generated directly through it.
var obj = new Object();
Note that by
var obj = new Object()
the wording of new objects, and the literal wording of thevar obj = {}
equivalent. Or, the former the latter is just a simple wording.
Object
Usage and tools constructor method is very similar, almost identical. When used, it can accept a parameter, if this parameter is a target, returns the object directly; if a value of the original type, the values corresponding to the object to be wrapped is returned (see "Object package" chapter).
var o1 = {a: 1};
var o2 = new Object(o1);
o1 === o2 // true
var obj = new Object(123);
obj instanceof Number // true
Although the use of similar, but Object(value)
the new Object(value)
semantics of the two are different, Object(value)
represent a value
turn as an object, new Object(value)
it represents a newly created object, its value is value
.
Object of static methods
The so-called "static method" refers to deploy in Object
the object itself.
Object.keys(),Object.getOwnPropertyNames()
Object.keys
Methods and Object.getOwnPropertyNames
methods for traversing an object's properties.
Object.keys
Parameter is an object method returns an array. Members of the array is the object itself (rather than inherited) all the property names.
var obj = {
p1: 123,
p2: 456
};
Object.keys(obj) // ["p1", "p2"]
Object.getOwnPropertyNames
The method and Object.keys
similar, but also takes an object as an argument and returns an array containing all the attributes of the object name itself.
var obj = {
p1: 123,
p2: 456
};
Object.getOwnPropertyNames(obj) // ["p1", "p2"]
For general objects, Object.keys()
and Object.getOwnPropertyNames()
returns the result is the same. When only involves non-enumerable properties will have different results. Object.keys
Method returns only enumerable properties (see "Description Object Object Properties" chapter), Object.getOwnPropertyNames
the method also returns the attribute name can not be enumerated.
var a = ['Hello', 'World'];
Object.keys(a) // ["0", "1"]
Object.getOwnPropertyNames(a) // ["0", "1", "length"]
The above code, the array length
properties are not enumerable property, so only in Object.getOwnPropertyNames
the method of the returned results.
Since the method of calculating the number of JavaScript provided object properties, it may be replaced by these two methods.
var obj = {
p1: 123,
p2: 456
};
Object.keys(obj).length // 2
Object.getOwnPropertyNames(obj).length // 2
In general, almost always used Object.keys
method, traversing the object's properties.
Other methods
In addition to the above-mentioned two methods, Object
there are many other static methods, one by one will be described in detail later.
Related methods (1) the model object properties
Object.getOwnPropertyDescriptor()
: For a description of the object of a property.Object.defineProperty()
: By describing the object, define a property.Object.defineProperties()
: Description object that defines a plurality of attributes.
(2) a method of controlling the state of the object
Object.preventExtensions()
: Object prevent expansion.Object.isExtensible()
: Determining whether the object is extended.Object.seal()
: Prohibited object configuration.Object.isSealed()
: Determining whether an object is disposed.Object.freeze()
: A frozen object.Object.isFrozen()
: To determine whether an object is frozen.
(3) Method prototype chain-related
Object.create()
: The method may specify the object and property of the prototype, a new object is returned.Object.getPrototypeOf()
: Gets the object ofPrototype
the object.
Object instance method
In addition to the static method, there are many methods defined in Object.prototype
objects. They are called instances method, all Object
instances of objects inherit these methods.
Object
Method instance of an object, mainly in the following six.
Object.prototype.valueOf()
: Returns the value of the current corresponding to the object.Object.prototype.toString()
: Returns the object corresponding to the current string.Object.prototype.toLocaleString()
: Returns the local string corresponding to the current object.Object.prototype.hasOwnProperty()
: To determine whether a property is the current object's own properties, or inherited property from the prototype object.Object.prototype.isPrototypeOf()
: Determining whether the current prototype of an object to another object.Object.prototype.propertyIsEnumerable()
: To determine whether a property enumerable.
This section describes four methods before the other two methods will be described later in related sections.
Object.prototype.valueOf()
valueOf
The method of action is to return an object "value", by default returns the object itself.
var obj = new Object();
obj.valueOf() === obj // true
Comparison of the above code obj.valueOf()
with obj
itself, the two are the same.
valueOf
The main purpose of the method is the default call this method (see "Data type conversion" chapter) when the JavaScript automatic type conversions.
var obj = new Object();
1 + obj // "1[object Object]"
The above object codes obj
to the digital 1
sum, this time will be called by default JavaScript valueOf()
method, obtaining obj
a value and then 1
added. So, if the custom valueOf
method, you can get the desired results.
var obj = new Object();
obj.valueOf = function () {
return 2;
};
1 + obj // 3
A custom code above obj
object valueOf
method, then 1 + obj
it was 3
. This method is equivalent to using a custom obj.valueOf
cover Object.prototype.valueOf
.
Object.prototype.toString()
toString
Method of action is to return a string object, return type string default.
var o1 = new Object();
o1.toString() // "[object Object]"
var o2 = {a:1};
o2.toString() // "[object Object]"
The above codes indicate to call an object toString
method, returns the string [object Object]
, the string description of the object type.
The string [object Object]
itself is not much use, but by customizing the toString
way for an object when automatic type conversions resulting in a string you want.
var obj = new Object();
obj.toString = function () {
return 'hello';
};
obj + ' ' + 'world' // "hello world"
The above codes indicate that when adding a string object is used, will automatically invoke toString
method. Since a custom toString
method, it returns a string hello world
.
Arrays, strings, functions, Date object are deployed custom toString
methods, covering Object.prototype.toString
methods.
[1, 2, 3].toString() // "1,2,3"
'123'.toString() // "123"
(function () {
return 123;
}).toString()
// "function () {
// return 123;
// }"
(new Date()).toString()
// "Tue May 10 2016 09:11:31 GMT+0800 (CST)"
In the above code, arrays, strings, functions, Date object to call toString
the method, and does not return [object Object]
because they have a custom toString
method, overwriting the original method.
Application of toString (): Analyzing Data Type
Object.prototype.toString
Method returns the object type string, can be used to determine a value type.
var obj = {};
obj.toString() // "[object Object]"
The above empty object code that calls toString
a method, the result returns a string object Object
, wherein the second Object
represents the value of the constructor. This is a very useful diagnostic data types.
Since the instance of the object may be a custom toString
method, overwrite Object.prototype.toString
method, so in order to obtain a string type is preferably used as Object.prototype.toString
the method. By function call
method, you can call this method on any value, to help us determine the type of the value.
Object.prototype.toString.call(value)
The above code indicates to value
call this value Object.prototype.toString
method.
Different data types Object.prototype.toString
method returns a value as follows.
- Value: return
[object Number]
. - String: return
[object String]
. - Boolean value: return
[object Boolean]
. - undefined: return
[object Undefined]
. - null: return
[object Null]
. - Array: return
[object Array]
. - arguments object: return
[object Arguments]
. - Function: return
[object Function]
. - Error object: return
[object Error]
. - Date object: return
[object Date]
. - RegExp object: return
[object RegExp]
. - Other objects: return
[object Object]
.
That is to say, Object.prototype.toString
we can see a value in the end is what type.
Object.prototype.toString.call(2) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"
Using this feature, you can write over a typeof
more accurate determination function of the type of operator.
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"
In the above type
basis functions, the method can also add some special type of data is determined.
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
['Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp'
].forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});
type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true
Object.prototype.toLocaleString()
Object.prototype.toLocaleString
Methods and toString
return the same result, but also returns a string value.
var obj = {};
obj.toString(obj) // "[object Object]"
obj.toLocaleString(obj) // "[object Object]"
The main role of this method is to set aside an interface, so a variety of objects that implement their own version toLocaleString
, to return specific values for certain geographies.
var person = {
toString: function () {
return 'Henry Norman Bethune';
},
toLocaleString: function () {
return '白求恩';
}
};
person.toString() // Henry Norman Bethune
person.toLocaleString() // 白求恩
The above code, the toString()
method returns a string general object, toLocaleString()
the method returns the local string.
Currently, there are three objects customized toLocaleString
approach.
- Array.prototype.toLocaleString()
- Number.prototype.toLocaleString()
- Date.prototype.toLocaleString()
For example, the instance of the object date toString
and toLocaleString
the return value is not the same, but toLocaleString
the area where the return value set by the user associated with.
var date = new Date();
date.toString() // "Tue Jan 01 2018 12:01:33 GMT+0800 (CST)"
date.toLocaleString() // "1/01/2018, 12:01:33 PM"
Object.prototype.hasOwnProperty()
Object.prototype.hasOwnProperty
The method takes a string as an argument and returns a Boolean value that indicates whether the object instance itself has the property.
var obj = {
p: 123
};
obj.hasOwnProperty('p') // true
obj.hasOwnProperty('toString') // false
In the above code, the object obj
itself has p
property is returned true
. toString
Property is inherited, so return false
.
Reference links
- Axel Rauschmayer, Protecting objects in JavaScript
- kangax, Understanding delete
- Jon Bretman, Type Checking in JavaScript
- Cody Lindley, Thinking About ECMAScript 5 Parts
- Bjorn Tipling, Advanced objects in JavaScript
- Javier Márquez, JavaScript properties are enumerable, writable and configurable
- Rafaeli Sella, Native JavaScript the Data-the Binding : using the access function implementation model and the view of the two-way binding
- Lea Verou, Copying object properties, the robust way