Object

Overview

JavaScript natively provides the Object object (note that the first O is capitalized). This chapter introduces various methods of the object native.

All other objects in JavaScript inherit from the Object object, that is, those objects are all instances of Object.

The native methods of the Object are divided into two categories: the methods of the Object itself and the instance methods of the Object.

(1) The method of the Object object itself

The so-called "own method" is a method directly defined in the Object object.

Object.print = function (o) {
  console.log(o);
};

In the above code, the print method is directly defined on the Object object.

(2) Instance method of Object

The so-called instance method is the method defined on the Object prototype object Object.prototype. It can be used directly by the Object instance.

Object.prototype.print = function () {
  console.log(this);
};

var obj = new Object();
obj.print(); // Object

In the above code, Object.prototype defines a print method, and then generates an instance of Object obj. obj directly inherits the properties and methods of Object.prototype, and you can directly use obj.print to call the print method. In other words, the print method of the obj object essentially calls the Object.prototype.print method.

For a detailed explanation of the prototype object object.prototype, see the chapter "Object-oriented Programming". As long as you know here, all the properties and methods defined on the Object.prototype object will be shared by all instance objects.

The following first introduces the usage of Object as a function, and then introduces the native methods of the Object object, which is divided into two parts: the method of the object itself (also known as the "static method") and the instance method.

Object()

Object itself is a function, which can be used as a tool method to convert any value into an object. This method is often used to ensure that a value must be an object.

If the parameter is empty (or undefined and null), Object() returns an empty object.

var obj = Object();
// Equivalent to
var obj = Object(undefined);
var obj = Object(null);

obj instanceof Object; // true

The meaning of the above code is to convert undefined and null into objects, and the result is an empty object obj.

The instanceof operator is used to verify whether an object is an instance of the specified constructor. obj instanceof Object returns true, which means that the obj object is an instance of Object.

If the parameter is a primitive type value, the Object method converts it to an instance of the corresponding packaging object (see the chapter "Packaging Objects of Primitive Types").

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, the parameters of the Object function are values ​​of various primitive types, and converted into objects are the packaging objects corresponding to the primitive type values.

If the parameter of the Object method is an object, it always returns the object, that is, no conversion is required.

var arr = [];
var obj = Object(arr); // return the original array
obj === arr; // true

var value = {};
var obj = Object(value); // return the original object
obj === value; // true

var fn = function () {};
var obj = Object(fn); // return to the original function
obj === fn; // true

Using this, you can write a function that determines whether a variable is an object.

function isObject(value) {
  return value === Object(value);
}

isObject([]); // true
isObject(true); // false

Object constructor

Object can be used not only as a tool function, but also as a constructor function, that is, you can use the new command before.

The primary purpose of the Object constructor is to directly generate new objects through it.

var obj = new Object();

Note that generating a new object through the writing of var obj = new Object() is equivalent to the writing of literal var obj = {}. In other words, the latter is just a simple way of writing the former.

The usage of the Object constructor is very similar to the tool method, almost exactly the same. When using, you can accept a parameter, if the parameter is an object, it will directly return this object; if it is a primitive type value, it will return the packaging object corresponding to the value (see the chapter "Packaging Objects" for details).

var o1 = { a: 1 };
var o2 = new Object(o1);
o1 === o2; // true

var obj = new Object(123);
obj instanceof Number; // true

Although the usage is similar, the semantics of Object(value) and new Object(value) are different. Object(value) means to convert value into an object, new Object(value) It means that a new object is generated, and its value is value.

Static method of Object

The so-called "static method" refers to the method deployed in the Object object itself.

Object.keys(), Object.getOwnPropertyNames()

Both the Object.keys method and the Object.getOwnPropertyNames method are used to traverse the properties of the object.

The parameter of the Object.keys method is an object, which returns an array. The members of the array are all property names of the object itself (not inherited).

var obj = {
  p1: 123,
  p2: 456,
};

Object.keys(obj); // ["p1", "p2"]

The Object.getOwnPropertyNames method is similar to Object.keys, it also accepts an object as a parameter and returns an array containing all the property names of the object itself.

var obj = {
  p1: 123,
  p2: 456,
};

Object.getOwnPropertyNames(obj); // ["p1", "p2"]

For general objects, the results returned by Object.keys() and Object.getOwnPropertyNames() are the same. Only when non-enumerable properties are involved, will there be different results. The Object.keys method only returns enumerable properties (see the chapter "Description of Object Properties" for details), and the Object.getOwnPropertyNames method also returns non-enumerable property names.

var a = ["Hello", "World"];

Object.keys(a); // ["0", "1"]
Object.getOwnPropertyNames(a); // ["0", "1", "length"]

In the above code, the length property of the array is a non-enumerable property, so it only appears in the return result of the Object.getOwnPropertyNames method.

Since JavaScript does not provide a method for calculating the number of object properties, these two methods can be used instead.

var obj = {
  p1: 123,
  p2: 456,
};

Object.keys(obj).length; // 2
Object.getOwnPropertyNames(obj).length; // 2

Under normal circumstances, the Object.keys method is almost always used to traverse the properties of an object.

Other methods

In addition to the two methods mentioned above, Object has many other static methods, which will be introduced in detail later.

(1) Related methods of object attribute model

-Object.getOwnPropertyDescriptor(): Get the description object of a certain property. -Object.defineProperty(): Define a property by describing the object. -Object.defineProperties(): Define multiple properties by describing the object.

(2) Method of controlling the state of the object

-Object.preventExtensions(): Prevent object extensions. -Object.isExtensible(): Determine whether the object is extensible. -Object.seal(): Object configuration is prohibited. -Object.isSealed(): Determine whether an object is configurable. -Object.freeze(): Freeze an object. -Object.isFrozen(): Determine whether an object is frozen.

(3) Prototype chain related methods

-Object.create(): This method can specify the prototype object and properties, and return a new object. -Object.getPrototypeOf(): Get the Prototype object of the object.

Object instance methods

In addition to static methods, there are many methods defined in the Object.prototype object. They are called instance methods, and all instance objects of Object inherit these methods.

There are mainly the following six methods of Object instance objects.

-Object.prototype.valueOf(): Returns the value corresponding to the current object. -Object.prototype.toString(): Returns the string form corresponding to the current object. -Object.prototype.toLocaleString(): Returns the locale string format corresponding to the current object. -Object.prototype.hasOwnProperty(): Determine whether a property is the property of the current object itself or is inherited from the property of the prototype object. -Object.prototype.isPrototypeOf(): Determine whether the current object is the prototype of another object. -Object.prototype.propertyIsEnumerable(): Determine whether a property is enumerable.

This section introduces the first four methods, and the other two methods will be introduced in related chapters later.

Object.prototype.valueOf()

The function of the valueOf method is to return the "value" of an object, which returns the object itself by default.

var obj = new Object();
obj.valueOf() === obj; // true

The above code compares obj.valueOf() and obj itself, the two are the same.

The main purpose of the valueOf method is that JavaScript will call this method by default during automatic type conversion (see the chapter "Data Type Conversion" for details).

var obj = new Object();
1 + obj; // "1[object Object]"

The above code adds the object obj to the number 1, then JavaScript will call the valueOf() method by default to find the value of obj and then add it to 1. So, if you customize the valueOf method, you can get the desired result.

var obj = new Object();
obj.valueOf = function () {
  return 2;
};

1 + obj; // 3

The above code customizes the valueOf method of the obj object, so 1 + obj gets 3. This method is equivalent to using a custom obj.valueOf, overwriting Object.prototype.valueOf.

Object.prototype.toString()

The function of the toString method is to return the string form of an object, and the type string is returned by default.

var o1 = new Object();
o1.toString(); // "[object Object]"

var o2 = { a: 1 };
o2.toString(); // "[object Object]"

The above code indicates that calling the toString method for an object will return the string [object Object], which indicates the type of the object.

The string [object Object] itself is not very useful, but by customizing the toString method, you can make the object get the desired string form during automatic type conversion.

var obj = new Object();

obj.toString = function () {
  return "hello";
};

obj + "" + "world"; // "hello world"

The above code indicates that when the object is used for string addition, the toString method is automatically called. Since the toString method is customized, the string hello world is returned.

Arrays, strings, functions, and Date objects are each deployed with a custom toString method, which overrides the Object.prototype.toString method.

[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, and Date objects call the toString method, but will not return [object Object], because they all customize the toString method, overwriting the original method.

Application of toString(): Judge the data type

The Object.prototype.toString method returns the type string of the object, so it can be used to determine the type of a value.

var obj = {};
obj.toString(); // "[object Object]"

The above code calls the toString method of the empty object, and the result returns a string object Object, where the second Object represents the value's constructor. This is a very useful way to determine the type of data.

Since the instance object may customize the toString method and override the Object.prototype.toString method, in order to get the type string, it is best to use the Object.prototype.toString method directly. Through the call method of the function, this method can be called on any value to help us determine the type of this value.

Object.prototype.toString.call(value);

The above code means that the Object.prototype.toString method is called on the value of value.

The return values ​​of the Object.prototype.toString method of different data types are as follows.

-Number: 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: returns [object Date]. -RegExp object: return [object RegExp]. -Other objects: return [object Object].

This means that Object.prototype.toString can tell what type a value is.

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 a more accurate type judgment function than the typeof 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"

On the basis of the above type function, you can also add a method for judging a certain type of data.

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()

The Object.prototype.toLocaleString method returns the same result as toString, and it also returns a value in string form.

var obj = {};
obj.toString(obj); // "[object Object]"
obj.toLocaleString(obj); // "[object Object]"

The main function of this method is to set aside an interface for various objects to implement their own version of toLocaleString to return specific values ​​for certain regions.

var person = {
  toString: function () {
    return "Henry Norman Bethune";
  },
  toLocaleString: function () {
    return "Bethune";
  },
};

person.toString(); // Henry Norman Bethune
person.toLocaleString(); // Bethune

In the above code, the toString() method returns the general string form of the object, and the toLocaleString() method returns the local string form.

Currently, there are mainly three objects that customize the toLocaleString method.

-Array.prototype.toLocaleString() -Number.prototype.toLocaleString() -Date.prototype.toLocaleString()

For example, the return values ​​of toString and toLocaleString for date instance objects are different, and the return value of toLocaleString is related to the locale set by the user.

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()

The Object.prototype.hasOwnProperty method accepts a string as a parameter and returns a boolean value indicating whether the instance object 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 the p attribute, so it returns true. The toString property is inherited, so false is returned.