Home > Web Front-end > JS Tutorial > JavaScript Advanced Programming (3rd Edition) Study Notes 6 First Understanding of JS Objects_Basic Knowledge

JavaScript Advanced Programming (3rd Edition) Study Notes 6 First Understanding of JS Objects_Basic Knowledge

WBOY
Release: 2016-05-16 17:49:12
Original
1101 people have browsed it

You can put anything you want in the house - if you have enough aesthetic skills, you can even try to build a room within a room - of course, for the convenience of management, we will remove all the things stored in the house. The last name that is not repeated, such as the names of various medicines in the medicine room. In ECMAScript, you can store any data you want in an object. Similarly, we need to give the stored data a name - that is, the attribute name of the object, and then store various data. Let’s look at the definition of object in ECMA-262: a collection of unordered attributes, whose attributes can contain simple data type values, objects or functions.

Entering the object, I started to get a little excited. To be honest, it reminded me of the original reason why I made this series of study notes. It was because the book’s in-depth discussion of objects made my knowledge of JavaScript change from the client side. The verification gadget has been transformed into a powerful object-oriented scripting language, but I am also having a little difficulty now, because there are too many things that need to be refined about objects, and I don’t know where to start, for example, if I want to go deeper. Understanding the concepts of objects, scope, execution environment, and closures are definitely inseparable, but if you start executing environments and closures without even mentioning the concept of objects, it feels like a castle in the air. But after thinking about it again, I felt relieved. After all, these are just my personal study notes, not a textbook. I can use the method I like to make my own notes (in fact, in the previous chapter, I consciously I like to repeat things that I think are interesting), but of course I try to make these notes in an easy-to-understand way.

Object type

Corresponding to 5 simple data types (Undefined, Null, Boolean, Number, String), Object is also a data type. It's just that this data type is special. Not only can it access ordinary data like a simple data type, but it can also access action behavior as a special kind of data.

1. Object instance

Each data type has a corresponding value. For example, the Undefined type has only one value undefined, and the number 5 is a value of the Number type. For object types, we call values ​​object instances. So what (value) instances can object types have? Any object is a value (instance) of the object type. For example, a simple type wrapper object (Boolean, Number, String) is a value (instance) of the object type.

2. Object literal

Since any object is an instance of the object type, how to represent the object instance? Or how do we write out object instances during communication? The values ​​of simple data types are easy to represent. For example, the symbol "5" represents the number 5, and the symbol "true" represents the Boolean value true. These are called literals. So, are there any object literals? The answer is yes, object literals are represented by a pair of curly brackets ({}). For example:

Copy code The code is as follows:

{
name:'linjisong',
getName:function(){
return this.name;
}
}

The outermost pair of curly brackets ({}) here represents this is an object literal. In addition, there is the concept of array literal. In ECMAScript, array Array is an object instance that inherits Object. Through this object instance, an instance of the array type can be created. An instance of the array type can also be directly represented by an array literal. The method is as follows:
Copy code The code is as follows:

[{
name:'linjisong ',
age:29
},{
name:'oulinhai',
age:23
}]

Here a pair of square brackets ([]) are used to represent an array, which is an array containing two objects. Through object literals and array literals, unimaginably powerful expressiveness is formed. In fact, the popular JSON data format is based on this.

3. Create an object instance

Friends who are familiar with general object-oriented know that to create an instance of a class, you must first define the class and then use the new keyword to create an instance of this class (don't tell me that you can also use reflection, I can't learn Java well...). But in ECMAScript, there is no concept of class at all. So, how to create an object instance?

Although there is no class in ECMAScript, there is a somewhat similar concept. Functions play this role. Object instances can be created through the new operator and functions - each object instance has a The function used to create this instance. The most basic function is Object(), which is a function used to create the most general objects. Others such as Number() function can be used to create instances of Number objects, and Boolean() function can be used to create instances of Boolean objects. :
Copy code The code is as follows:

var obj = new Object();//Object () function, creates the most general object instance
var num = new Number(1);//Number() function, creates an instance of Number object
var boo = new Boolean(true);//Boolean( ) function, creates an instance of Boolean object
console.info(typeof num);//object
console.info(typeof Number(1));//number
console.info(typeof boo); //object
console.info(typeof Boolean(true));//boolean

(1) As you can see, to create an object instance, you first need to have a function (called Constructor), when this function is called using new, it creates an object instance. When new is not used, it is just a function call in the usual sense (if this function returns an instance internally, the function call can also create an object).

(2) The so-called built-in objects are actually built-in functions that create object instances. Different functions create different built-in objects.

(3) Regarding whether to use the new operator, my suggestion is to use it. If you don’t use the new operator, in some cases the results will be unexpected, like the 5th example in the above example. , line 7, does not actually create an object, but is just an ordinary function call. The function of this call is to convert the data type.

(4) When using new to create an object instance, if you call the constructor without passing in parameters, you can also omit the subsequent function call operator (()). Of course, this feature is not worth promoting. things.

(5) If you need to create an instance of a custom object, you first need to define a constructor, and then use the new operator to call the instance. It should be noted here that if you forget new, you may pollute the global environment:
Copy code The code is as follows:

function Person(){//First define a (constructor) function for creating object instances
this.name = 'linjisong';
this.age = 29;
}

var person = new Person();//Call (constructor) function to create object instance
console.info(person.age);//29

try{
console. info(age);//In order to demonstrate the situation of forgetting to use new, the global age is output here first. Since it is undefined, an exception is thrown
}catch(e){
console.info(e);// ReferenceError
}
var person2 = Person();//When you forget to use new, it is just an ordinary function call. Since the function does not return, person2 is undefined here
console.info(person2); //undefined
console.info(age);//29, new is not used, and the internal this points to the global scope, because age can be accessed globally

To avoid this Question, you can modify the constructor:
Copy code The code is as follows:

function Person() {
if(this instanceof Person)
{
this.name = 'linjisong';
this.age = 29;
}else{
return new Person();
}
}
var person2 = Person();
console.info(person2.age);//29, you can access person2’s age
console.info(age);/ /There is no definition of age in the global environment, and an exception is thrown


This constructor first determines whether this value is of Person type. If not, it uses new call internally to ensure that the returned value must be a Person type instance. This method makes it possible to reconstruct the constructor. Perhaps Boolean(), Number(), and String() use this method in implementation to distinguish between constructors and conversion functions. If you omit new when calling Object(), the result can also return the object. It is estimated that similar processing is done in the background. In the same situation, there is also the function type constructor Function() that will be discussed later in this article.

(5) Some people may ask, since there are object literals, why do we need to use such a complicated way to create object instances? Wouldn’t it be enough to just write the object literals directly? Using object literals to create object instances does not use any functions at all. It seems that the above statement "each object instance has a function used to create this instance" is not correct.

First of all, the first question is, indeed, you can use object literals to create functions, and it is very concise. This is even the first creation method I recommend, but creating object instances in this way only requires Being able to create singleton instances is not applicable to those who need to create multiple object instances of the same type. Then the second question is to use object literals to create objects. In fact, it does not mean that there is no corresponding constructor, but the constructor is Object(), using object literals, new Object() may not be called in the background, but the created object still has attributes pointing to this function. This can be verified from the following code output:
Copy code The code is as follows:

var person = {};
console.info(person.constructor=== Object);//true

The constructor here is an attribute of each instance object, which is used to save the function that creates this object instance. This is what we will talk about below.

4. Object properties and methods

Each data type has its own characteristics. For example, a Number type value can be added to another Number type value. Characteristics, similarly, instances of object types also have some same characteristics, which are reflected in the fact that they all contain the following attributes and methods (methods are actually also a type of attribute, but if the value type of the attribute is a function, we also call it as method):

类别 属性/方法 说明
属性 constructor 指向用于创建当前对象的函数
方法 hasOwnProperty(propertyName) 检查给定的属性是否在当前对象实例中
propertyIsEnumerable(propertyName) 检查给定的属性是否能够是使用for-in语句来枚举
isPrototype(object) 检查传入的对象是否是另一个对象的原型
toLocalString() 返回对象的字符串表示,该字符串与执行环境的地区相对应
toString() 返回对象的字符串表示
valueOf() 返回对象的字符串、数值或布尔值表示,通常与toString()方法返回值相同

Note: On page 35 of "Advanced Programming with JavaScript (3rd Edition)", the first letter of Constructor is capitalized, which should be a typographical error.

There are two ways to access attributes and methods:

(1) Use the dot (.): such as person.name.

(2) Use square brackets ([]): such as person[name]. In this way, the square brackets can be a variable or expression inside, which allows you to access properties and properties whose names contain special symbols. method.

By combining for-in with hasOwnProperty (propertyName) here, we can iterate over the properties of the object instance itself without including the properties inherited from the prototype chain:
Copy code The code is as follows:

for(var propertyName in object){
 if(object.hasOwnPorperty(propertyName)){
  // Loop processing
 }
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template