JavaScript Advanced Programming (3rd Edition) Learning notes 6 initial knowledge of JS Object _ Basics

Source: Internet
Author: User
Tags access properties throw exception hasownproperty
You can put whatever you want in the house--if you have enough aesthetic attainments, you can even get a room to try--of course, for the convenience of management, we'll take a repeat name for everything that's stored in the house, like the names of drugs in the medicine room. In ECMAScript, you can store any data you want in the object, and again, we need to give a name to the stored data--that is, the object's property name, and then store all the data. Then look at the definition of objects in ECMA-262: A collection of unordered attributes that can contain simple data type values, objects, or functions.

Into the object, I began to be a little agitated, to tell you the truth, the first reason I remember doing this series of notes is that because of the depth of the book's discussion of the object, my knowledge of JavaScript has turned from a client-side validation gadget into a powerful object-oriented scripting language, but I'm a bit puzzled now, because about objects , there are too many things to be refined, a moment also do not know which point to cut, for example, to understand the object, scope, execution environment, closures, these concepts are certainly inseparable, but if the concept of the object did not say to start the implementation of the environment and closure, and feel like a castle in the atmosphere. But another thought, also relieved, this is only their own personal learning notes, it is not a textbook, I can use the way I like to do my own notes (in fact, in the previous chapter, I have consciously repeat what I think is interesting, this is the way I like), of course, I will still try to make these notes in a way that is easy to understand.

Object Type

Corresponds to 5 simple data types (Undefined, Null, Boolean, Number, String), objects (object) is a data type, but this data type is special, and it can access the usual data as simple data types. And the action behavior can be accessed as a special data.

1. Object instance

Each data type has a corresponding value, such as a undefined type with only one value undefined, and the number 5 is a value of type A. For object types, we refer to values as object instances, so what are the (value) instances of an object type? Any object is a value (instance) of an object type, such as a simple Type wrapper object (Boolean, number, String) is a value (instance) of an object type.

2, object literal quantity

Since any object is an instance of an object type, how does an object instance represent? Or how do we write examples of objects in the communication process? The value of a simple data type is very good, for example, with the symbol "5" for the number 5, the symbol "true" to represent the Boolean value true, these are called literal quantities, then, there is no object literal quantity? The answer is yes, the object literal is represented by a pair of curly braces ({}). Like what:
Copy Code code as follows:

{
Name: ' Linjisong ',
Getname:function () {
return this.name;
}
}

The outermost pair of braces ({}) here means that this is an object literal. In addition, there is the concept of an array literal, in ECMAScript, an array array is an object instance that inherits objects, through which an instance of an array type can be created, and an instance of an array type can be represented directly by the literal volume of an array, as follows:
Copy Code code as follows:

[{
Name: ' Linjisong ',
Age:29
},{
Name: ' Oulinhai ',
Age:23
}]

Here a pair of brackets ([]) is used to represent an array, which is an array that contains two objects. With object literals and arrays of literal quantities, it creates unimaginable power, in fact, the popular JSON data format is based on this.

3. Create an object instance

Familiar with General object-oriented friends know that to create an instance of a class, you first define the class and then use the New keyword to create an instance of the class (Don't tell me you can use reflection, my Java is not good ...) )。 But in ECMAScript, there is no concept of a class at all, so how do you create an object instance?

Although there are no classes in ECMAScript, there are some similar concepts that assume the role of a function that creates an object instance with the new operator and function-each object instance has a function to create the instance. The most basic function is the object (), which is the function used to create the most common object, other such as the number () function, which can be used to create an instance of the Number object, a Boolean () function that can be used to create an instance of a Boolean object:
Copy Code code as follows:

var obj = new Object ();//object () function to create the most common object instance
var num = new number (1);//number () function, creating an instance of the Number object
var boo = new Boolean (true);//boolean () function, creating an instance of a 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) You can see that to create an object instance, you first need to have a function (called a constructor) that uses the new call to create an object instance, which is simply a function call in the usual sense when you do not use new (if the function returns an instance internally, the function call can also create the object).

(2) The so-called built-in object is actually a built-in set of functions to create object instances, and different functions create different built-in objects.

(3) about if you want to use the new operator, my advice is to use, if you do not use the new operator, in some cases the results will be unexpected, as in the example of the 5th, 7 lines, in fact, did not create objects, but only ordinary function calls, the function of this call is to transform the data type.

(4) When creating an object instance using new, if the calling constructor does not require incoming arguments, you can omit the following function call Operator (()), and of course, this feature is not something to preach.

(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 call to create the instance. It should be noted that if you forget about new, you may contaminate the global environment:
Copy Code code as follows:

function person () {///first defines a (constructor) functions for creating an instance of an object
this.name = ' Linjisong ';
this.age = 29;
}

var person = new person ();//Call (constructor) function Create object instance
Console.info (person.age);//29

try{
Console.info (age); In order to demonstrate forgetting to use new, this first outputs the global age, which throws an exception because it is undefined
}catch (e) {
Console.info (e);//referenceerror
}
var person2 = person ()//Forget to use new, just ordinary function call, because the function does not return, here Person2 is undefined
Console.info (Person2);//undefined
Console.info (age);//29, not using new, the internal this points to the global scope because it can be accessed globally

To avoid this problem, you can modify the constructor:
Copy Code code as follows:

function person () {
if (this instanceof person)
{
this.name = ' Linjisong ';
this.age = 29;
}else{
Return to new person ();
}
}
var person2 = person ();
Console.info (person2.age);//29, you can access the age of Person2.
Console.info (age);//No Age definition in global environment, throw exception


This constructor first determines whether the this value is a person type and, if not, uses the new call internally to ensure that the returned value must be an instance of the person type. This approach makes the refactoring constructor possible, and perhaps Boolean (), number (), String () is used in this way to differentiate between constructors and conversion functions. If you omit new when you call Object (), the result can return the object, presumably in the background, as well as the function type constructor function (), which is the later part of this article.

(5) Some people may ask, since there are objects literal, why to use such a complex way to create object instances, directly write object literal volume is not finished? To create an object instance with an object literal, there is no function at all, and it seems incorrect to say that each object instance has a function to create this instance.

First question, indeed, you can use object literals to create functions, and it's also very concise, which is even one of the first things I recommend, but creating an object instance in this way can only create an instance of a singleton that doesn't apply to creating multiple object instances of the same type, and then the second question, Creates an object with the literal amount of the object, in fact, there is no constructor, just the constructor is object (), the object literal, the background may not call new object (), but the created object still has properties that point to the function, which can be validated from the following code output:
Copy Code code as follows:

var person = {};
Console.info (person.constructor===object);//true

The constructor here is a property of each instance object that holds the function that created the instance of the object, which is the following.

4. Object Properties and Methods

Each data type has its own commonalities, such as the number type value with an attribute that can be added to another number type value, as well as instances of object types that have the same attributes, which are embodied in the following attributes and methods (the method is actually a property, Just the value type of the attribute is a function, we also call it a method:

Category Properties/Methods Description
Property Constructor Point to the function used to create the current object
Method hasOwnProperty (PropertyName) Checks whether the given property is in the current object instance
propertyIsEnumerable (PropertyName) Checks whether a given property can be enumerated by using the For-in statement
Isprototype (object) Check if the incoming object is a prototype of another object
Tolocalstring () Returns the string representation of an object that corresponds to the region where the environment is executed
ToString () Returns the string representation of an object
ValueOf () Returns the string, numeric, or Boolean value of an object, usually the same as the ToString () method return value

Note: constructor on page 35th of the JavaScript Advanced Programming (3rd Edition) will capitalize the first letter, which should be a typographical error.

There are two ways to access properties and methods:

(1) Use dot number (.): such as Person.name.

(2) using square brackets ([]): such as Person[name], in this way, the square brackets can be a variable or an expression, which allows access to properties and methods that contain special symbols.

By combining For-in and the hasownproperty here (PropertyName), we can traverse the properties of the object instance itself without including the attributes inherited from the prototype chain:
Copy Code code as follows:

For (Var propertyname in object) {
if (Object.hasownporperty (PropertyName)) {
Cyclic processing
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.