javascript: Object Object

Object Object

Outline

JavaScript provides native Objectobjects (note that the chapeau Ois capitalized), this chapter describes the various methods of the object native.

All other objects are inherited from JavaScript Objectobjects, those objects are Objectinstances.

ObjectNative method object into two categories: Objectprocess itself and the Objectexample method.

(1) Objectthe object itself method

The so-called "own way" is defined directly in the Objectmethod of the object.

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

In the above code, printthe method is defined directly Objecton the object.

(2) ObjectExamples of the method

Examples of the method is defined in a so-called Objectprototype object Object.prototypemethods on. It can be Objectused as examples.

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

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

The above code, Object.prototypedefines a printmethod, and then generate a Objectexample obj. objDirectly inherited Object.prototypeproperties and methods can be used directly obj.printinvoke printmethods. In other words, objthe object of the printmethod is essentially calling Object.prototype.printmethod.

About the prototype object of object.prototypea detailed explanation, see "Object Oriented Programming" section. Here just know that it is defined in Object.prototypethe object properties and methods above, will be shared by all instances of the object can be.

The following describes the first Objectas a function of usage, and then introduce Objectthe native object method, the object itself into (also known as "static method") and the example method of two parts.

Object()

ObjectItself 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 undefinedand 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 undefinedand nullconverted to the object, the result of a null object obj.

instanceofOperator is used to verify whether a specified object is an instance constructor. obj instanceof ObjectReturn true, it means objthe object is Objectan instance.

If the parameter is a value of the original type, Objecta 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, Objectthe 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 Objectmethod 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

ObjectNot only can function as a tool to use, you can also use as a constructor, which can be used in front of newthe command.

ObjectThe 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 the var obj = {}equivalent. Or, the former the latter is just a simple wording.

ObjectUsage 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 valueturn 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 Objectthe object itself.

Object.keys(),Object.getOwnPropertyNames()

Object.keysMethods and Object.getOwnPropertyNamesmethods for traversing an object's properties.

Object.keysParameter 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.getOwnPropertyNamesThe method and Object.keyssimilar, 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.keysMethod returns only enumerable properties (see "Description Object Object Properties" chapter), Object.getOwnPropertyNamesthe 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 lengthproperties are not enumerable property, so only in Object.getOwnPropertyNamesthe 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.keysmethod, traversing the object's properties.

Other methods

In addition to the above-mentioned two methods, Objectthere 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 of Prototypethe object.

Object instance method

In addition to the static method, there are many methods defined in Object.prototypeobjects. They are called instances method, all Objectinstances of objects inherit these methods.

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

valueOfThe 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 objitself, the two are the same.

valueOfThe 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 objto the digital 1sum, this time will be called by default JavaScript valueOf()method, obtaining obja value and then 1added. So, if the custom valueOfmethod, you can get the desired results.

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

1 + obj // 3

A custom code above objobject valueOfmethod, then 1 + objit was 3. This method is equivalent to using a custom obj.valueOfcover Object.prototype.valueOf.

Object.prototype.toString()

toStringMethod 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 toStringmethod, 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 toStringway 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 toStringmethod. Since a custom toStringmethod, it returns a string hello world.

Arrays, strings, functions, Date object are deployed custom toStringmethods, covering Object.prototype.toStringmethods.

[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 toStringthe method, and does not return [object Object]because they have a custom toStringmethod, overwriting the original method.

Application of toString (): Analyzing Data Type

Object.prototype.toStringMethod 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 toStringa method, the result returns a string object Object, wherein the second Objectrepresents the value of the constructor. This is a very useful diagnostic data types.

Since the instance of the object may be a custom toStringmethod, overwrite Object.prototype.toStringmethod, so in order to obtain a string type is preferably used as Object.prototype.toStringthe method. By function callmethod, 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 valuecall this value Object.prototype.toStringmethod.

Different data types Object.prototype.toStringmethod 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.toStringwe 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 typeofmore 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 typebasis 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.toLocaleStringMethods and toStringreturn 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 toLocaleStringapproach.

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

For example, the instance of the object date toStringand toLocaleStringthe return value is not the same, but toLocaleStringthe 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.hasOwnPropertyThe 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 objitself has pproperty is returned true. toStringProperty is inherited, so return false.

Reference links

Guess you like

Origin www.cnblogs.com/wbyixx/p/12496981.html