Exploring JavaScript: Array Methods, Prototypal Chain Inheritance, and JSON

Table of contents

Array object

Constructor

static method

Array.isArray()

instance method

valueOf()

toString()

object inheritance

Constructor Disadvantages

The role of the prototype attribute

prototype chain

 The process of reading a property of an object:

constructor property

instanceof operator

JSON

Advantages of JSON:

JSON has strict rules about the type and format of values.

JSON object

JSON.stringify() [JS format -> JSON format]

first parameter

second parameter

third parameter

toJSON() method of the parameter object

JSON.parse() [JSON format -> JS format]


Array object

Constructor

Array is a native object of javaScript, and it is also a constructor that can be used to generate new arrays

static method

Array.isArray()

The Array.isarray method returns a boolean indicating whether the argument is an array . He can make up for the lack of typeof algorithm

For example:

    <script>
        var arr = [1, 2, 3];
        var a = typeof arr;
        var b = Array.isArray(arr)
        console.log(a, b);
    </script>

result:

instance method

valueOf()

The valueOf method is a method that all objects have, indicating that the object is evaluated

The valueof method of different objects is not consistent, the valueof of the array is released to return the array itself

For example:

    <script>
        var arr = [1, 2, 3]
        var arr_result = arr.valueOf()
        console.log(arr_result);
    </script>

result: 

toString()

The toString method is also a general method of the object

The toString method of an array returns the string form of the array

For example:

    <script>
        var arr = [1, 2, 3]
        var arr_result = arr.toString()
        console.log(arr_result);
    </script>

result:

object inheritance

By inheriting the B object, the A object can directly have all the properties and methods of the B object. This is very useful for code reuse.

Most object-oriented programming languages ​​implement object inheritance through " classes" . The inheritance of traditional JavaScript language is not through class, but through "prototype object" (prototype) (class == prototype object)

Objects are reifications of classes

Constructor Disadvantages

JS generates new objects through constructors, so constructors can be regarded as templates for objects. The properties and methods of the instance object can be defined inside the constructor

For example:

    <script>
        function Cat(name, color) {
            this.name = name;
            this.color = color;
        }
        var cat1 = new Cat('大毛', '白色');

        cat1.name // '大毛'
        console.log(cat1.name);
        cat1.color // '白色'
        console.log(cat1.color);
    </script>

In the above code, the Cat function is a constructor . The name attribute and the color attribute are defined inside the function . All instance objects (cat1 in the above example) will generate these two attributes, that is, these two attributes will be defined on the instance object.

result:

Proposition of the problem : Properties cannot be shared between multiple instances of the same constructor, resulting in a waste of system resources

Problem Solving : JavaScript's prototype object (prototype)

The role of the prototype attribute

The design idea of ​​the JavaScript inheritance mechanism is that all properties and methods of the prototype object can be shared by the instance object. That is to say, if properties and methods are defined on the prototype, then all instance objects can be shared , which not only saves memory, but also reflects the connection between instance objects.

js stipulates that each function has a Prototype property, which executes an object

For ordinary functions, this attribute is basically useless, but for constructors, when an instance is generated, this attribute will automatically generate the prototype of the instance object.

For example:

function Animal(name) {
    this.name = name;
}
Animal.prototype.color = 'white';//为Animal原型对象添加一个属性white
var cat1 = new Animal('大毛');
var cat2 = new Animal('二毛');

cat1.color // 'white'
cat2.color // 'white'\
console.log(cat1.color, cat2.color);

In the above code, the prototype property of the constructor Animal is the prototype object of the instance objects cat1 and cat2. Add a color attribute and method miaomiao to the prototype object, and as a result, the instance objects all share this attribute and method.

result:

 

The result shows that the instance object can use the properties and methods of the prototype object normally

Note :

As long as the prototype object is modified, the change will immediately be reflected in all instance objects

If the instance object itself has a certain property or method, it will not take the prototype object to find this property or method (that is, its own priority is greater than that of the prototype object)

The role of the prototype object is to define the properties and methods shared by all instance objects.

prototype chain

JavaScript stipulates that all objects have their own prototype object (prototype). On the one hand, any object can serve as the prototype of other objects; on the other hand, since an object is also an object, it also has its own prototype. Thus a " prototype chain " is formed : object to prototype, to prototype's prototype...

Prototype chain inheritance : the prototype object defines a property

If you trace back layer by layer, the prototypes of all objects can eventually be traced back to Object.prototype, that is, the prototype property of the Object constructor . That is, all objects inherit the properties of Object.prototype.

The prototype of Object.prototype is null, null has no properties and methods, and has its own prototype, so the end of the prototype chain is null

 The process of reading a property of an object :

When reading a property of an object, the JavaScript engine first looks for the property of the object itself. If it cannot find it, it goes to its prototype. If it still cannot find it, it goes to the prototype of the prototype to find it. If Object.prototype is not found up to the topmost level, undefined is returned.

Override : If both the object itself and its prototype define a property with the same name, then the property of the object itself is read first

Note: Going up one level, looking for a certain attribute on the entire prototype chain has an impact on performance. The higher the prototype object whose property you are looking for has a greater impact on performance. If looking for a property that doesn't exist, the entire prototype chain will be traversed.

constructor property

The prototype object has a constructor attribute, which by default points to the constructor where the prototype object is located

The function of the constructor attribute is: you can know which constructor generated an instance object.

For example:

function F() { };
var f = new F();

a = f.constructor === F // true
b = f.constructor === RegExp // false
console.log(a, b);

result:

 According to it, we can know that the constructor attribute determines the constructor of the instance object f when F is not RegExp

instanceof operator

The instanceof operator returns a boolean indicating whether the object is an instance of a constructor

The left side of the instanceof operator is the instance object, and the right side is the constructor. It checks whether the prototype object (prototype) of the constructor on the right is on the prototype chain of the object on the left.

The principle of instanceof is to check whether the prototype property of the constructor on the right is on the prototype chain of the object on the left. There is a special case where there is only null object on the prototype chain of the left object. At this time, the instanceof judgment will be distorted.

For example:

var obj = Object.create(null);
typeof obj // "object"
obj instanceof Object // false

In the above code, Object.create(null) returns a new object obj whose prototype is null. The prototype property of the constructor Object on the right is not on the prototype chain on the left, so instanceof thinks that obj is not an instance of Object. This is the only case where the instanceof operator will be distorted (an object whose prototype is null) .

One use of the instanceof operator is to determine the type of a value.

For example:

var x = [1, 2, 3];
var y = {};
x instanceof Array // true
y instanceof Object // true

 According to the results, it can be known that x is an array and y is an object

Note : The instanceof operator can only be used on objects, not on primitive values.

JSON

JSON format (JavaScript Object Notation) is a text format for data exchange, the purpose is to replace the cumbersome and cumbersome XML format

Advantages of JSON :

It is easy to write and clear at a glance; it conforms to the native JavaScript syntax and can be directly processed by the interpretation engine without adding additional parsing code.

Each JSON object is a value, which may be an array or object, or a primitive value . In short, it can only be one value, not two or more values.

JSON has strict rules about the type and format of values.

  1. The value of the composite type can only be an array or an object, not a function, a regular expression object, or a date object.

  2. There are only four primitive types of values: string, number (must be expressed in decimal), Boolean and null (NaN (not a number), Infinity (infinity), -Infinity (infinitely small) and undefined (undefined definition)).

  3. Strings must be represented by double quotes, not single quotes.

  4. Object keys must be enclosed in double quotes.

  5. A comma cannot be added after the last member of an array or object.

The following are all valid JSON:

["one", "two", "three"]
{ "one": 1, "two": 2, "three": 3 }
{"names": ["张三", "李四"] }
[ { "name": "张三"}, {"name": "李四"} ]

The following are all invalid JSON:

{ name: "张三", 'age': 32 } // 属性名必须使用双引号
[32, 64, 128, 0xFFF] // 不能使用十六进制值
{ "name": "张三", "age": undefined } // 不能使用 undefined
{ "name": "张三",
"birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
"getName": function () {
return this.name;
}
} // 属性值不能使用函数和日期对象

Note: null, empty array, and empty object are all legal JSON values.

JSON object

JSON object is a native object of JavaScript, used to process JSON format data .

It has two static methods: JSON.stringify() and JSON.parse().

JSON.stringify() [JS format -> JSON format]

first parameter

Basic usage:

JSON. The stringify() method is used to convert a value into a JSON string. The string conforms to the JSON format and can be restored by the JSON.parse() method.

For example:

JSON.stringify('abc') // ""abc""
JSON.stringify(1) // "1"
JSON.stringify(false) // "false"
JSON.stringify([]) // "[]"
JSON.stringify({}) // "{}"
JSON.stringify([1, "false", false])
// '[1,"false",false]'
JSON.stringify({ name: "张三" })
// '{"name":"张三"}'

The above various types of values ​​will be converted to JSON strings

Note : For values ​​of primitive types, the conversion result will be enclosed in double quotes ""

special:

a = (JSON.stringify('foo') === "fool")
b = (JSON.stringify('foo') === "\"foo\"")
console.log(a, b);

In the above code, the string foo is converted to "\""foo"\"". This is because when restoring, the inner double quotes can let the js engine know that this is a string, not other types

result:

 If the property of the object is undefined, a function or an XML object, the property will be filtered by JSON.stringify().

If the members of the array are undefined, functions, or XML objects, these values ​​are converted to null.

If it is a regular object, it will be converted to an empty object.

second parameter

The JSON.stringify() method can also accept an array as the second parameter, specifying which properties of the parameter object need to be converted into strings

The second parameter can also be a function to change the return value of JSON.stringify().

example:

function f(key, value) {
    if (typeof value === "number") {
        value = 2 * value;
    }
    return value;
}

a = JSON.stringify({ a: 1, b: 2 }, f)
console.log(a);

The f function in the above code accepts two parameters, which are the key name and key value of the converted object. If the key is a number, it is multiplied by 2, otherwise it is returned as is.

result:

third parameter

JSON.stringify() can also accept a third parameter, which is used to increase the readability of the returned JSON string.

By default, a single-line string is returned, which is very unreadable for large JSON objects. The third parameter makes each attribute occupy a separate line, and adds the specified prefix (no more than 10 characters) to each attribute.

example:

// 默认输出
a = JSON.stringify({ p1: 1, p2: 2 })
console.log(a);
// 分行输出
b = JSON.stringify({ p1: 1, p2: 2 }, null, '\t')
console.log(b);

In the above example, the third attribute \t adds a tab character in front of each attribute, and then displays it in separate lines.

result:

The third attribute, if it is a number, represents the spaces (up to 10) added in front of each attribute.

toJSON() method of the parameter object

If the parameter object has a custom toJSON() method, then JSON.stringify() will use the return value of this method as a parameter, while ignoring other properties of the original object

example:

var user = {
    firstName: '三',
    lastName: '张',

    get fullName() {
        return this.lastName + this.firstName;
    },

    toJSON: function () {
        return {
            name: this.lastName + this.firstName
        };
    }
};

a = JSON.stringify(user)
console.log(a);

In the above code, JSON.stringify() finds that the parameter object has a toJSON() method, and directly uses the return value of this method as a parameter, while ignoring other parameters of the original object.

result:

One application of the toJSON method is to automatically convert regular objects to strings .

Because JSON.stringify() cannot convert regular expressions by default, but after setting the toJSON() method, regular objects can be converted.

example:

var obj = {
reg: /foo/
};
// 不设置 toJSON 方法时
JSON.stringify(obj) 
//结果: "{"reg":{}}"
// 设置 toJSON 方法时
RegExp.prototype.toJSON = RegExp.prototype.toString;
JSON.stringify(/foo/) 
//结果: ""/foo/""
hacker 平替写法 绕弯的写法

The above code deploys the toJSON() method on the prototype of the regular object and points it to the toString() method. Therefore, when converting to JSON format, the regular object first calls the toJSON() method to convert it into a string, and then is JSON.stringify () method processing.

JSON.parse() [JSON format -> JS format]

JSON, parse() method is used to convert JSON string to corresponding value.

For example:

JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"foo"') // "foo"
JSON.parse('[1, 5, "false"]') // [1, 5, "false"]
JSON.parse('null') // null
var o = JSON.parse('{"name": "张三"}');
o.name // 张三

If the incoming string is not in valid JSON format, the JSON.parse() method will report an error.

The JSON.parse() method can accept a processing function as the second parameter, and its usage is similar to the JSON.stringify() method.

Guess you like

Origin blog.csdn.net/qq_68163788/article/details/131107597