The original JS is this - the object properties

Primer

In the previous (original JS like this (2)) when just released on reading the article who may notice essay I had used "JavaScript in Everything Is an Object," saying, but then I found in after the error update Now get rid of this error argument. Also on an essentially dwells in the description thisin the end the circumstances under which binds to the target, the object concept in JavaScript looks really easy confusing. A look at the following example:

var strPrimitive = "I'm mamacat";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false

var strObject = new String("I'm mamacat");
typeof strObject; // "object"
strObject instanceof String; // true

strPrimitive.substr(8, 3); // "cat"

The same string assignment to the object, while the object is of type string for a while, but obviously not the object type of a variable or you can use object properties, Why is this so?

Type and built-in objects

JavaScript, a total of six major (language) types, namely string, number, boolean, null, undefinedand object, where the first five basic types are not objects (to nullbe typeof get is "object", which is language itself BUG). In addition to this, there are many special sub-type objects, such as arrays, functions and built-in objects.

Some looked at the names of built-in objects and simple basic types, such as it is String, Boolean, Objectand the like. These built-in objects from forms to see other object-oriented languages and "class" concept is almost, but as the article belongs, they are actually just some of the correspondence can be used to construct a sub-type of built-in functions only (not to confused , functions are objects, there is no contradiction). Can then return to the first example, strObjectby the built-in function / built-in objects Stringvariable configuration, the corresponding Stringsub-type, so it is an object, but strPrimitiveit is only one original literal.

Of course, the above example we look for the lowest strPrimitivecall substr()function, here it is because, JavaScript engine when needed, to convert the original literal into corresponding object, and then we convert natural methods can use to access the property a.

Object Properties

Then, on the above example, the Stringobject instances there will be a substr()function can be used, but according to previous articles know that these "functions" in itself does not belong to an object, which is essentially a function of the corresponding property of the object. Of course, even if we say that the object itself has some type of various properties, these properties are mostly in fact exist independently of, but in the form of a reference association with it, and before this is not contradictory to Know . These things are linked together, are called object properties .

Copy objects

Spots a newsletter, although the previous article mentioned, the above also repeatedly emphasized again just exist independently associated attribute in the form of reference, we still sometimes "deserved" the property is considered part of the object, and the most So one easy step on pit where the object is copied. Careful thought to know that when we copy an object, due to its nature itself is just a reference association, the "copy" the resulting object contains properties and reference properties point to the original object references but it is still the same location:

var ori = { a : 1};
var ori_copy = ori;
ori.a = 61;
ori_copy.a; // 61

Obviously, this is likely not the same and our expectations, and we want a real copy of the object is not perfect applicability of the scheme, the conventional practice is often the object serialization is about, then in order to get new deserialized to achieve the target copy of the object (such as using json). ES6 added a Object.assign()shallow copy to the object, the object is to practice all enumerable properties equal sign assigned to the new object. But it cautioned that the equals sign is not assigned the attribute assignment and meta information (attribute descriptor, described later), in the case where special attention should be required.

And an array of property access

Way to access the object associated with the property that is, through .or []operator access, obj.aand obj["a"]property access is essentially the same, but the difference between these two forms of access is only accessible in the attribute name can have strange symbols only. []Within the operator's throw is a string, in fact, attribute names are never strings. Of course, this concept may be more unexpected is that the array subscript access is not really an exception, or is converted to a digital string was only used.

// 对象的属性访问:
var tejilang = {1 : "Teji Wolf"};
tejilang instanceof Array; // false
tejilang["1"]; // "Teji Wolf"
tejilang[1]; // "Teji Wolf"

// 这回保证它是 Array
var macat = ["codingcat"];
macat instanceof Array; // true
macat.length; // 1
macat[0]; // "codingcat"
macat["0"]; // "codingcat"
macat.length = 20;
macat; // (20) ["codingcat", empty × 19]

Since they do not belong to an array subscript exceptions, that there must be an array of objects to control the behavior of other properties of the array itself, such as the above example, the macatlength of the array is the lengthproperty embodied by modifying its value also changes the performance of the external object itself form. Of course, since the array itself is an object, so we can put an array of key-value pairs to use when, but this approach usually does not make sense and will make people confused. JavaScript engines generally have done a different degree of optimization according to the type of object, so in addition to the readability of the code logic and rational use is how much you can improve performance.

There can be some other benefits of access by character or property, such as property name for ES6 be calculated. Of course, this article is not within the focus range ES6, so there will no longer discussed.

Attribute descriptor

Sometimes we may not want a property to be freely modified, sometimes we need to configure some additional information about the properties, starting from ES5, all attributes will have the ability to "property descriptor" (Property Descriptor) to control the properties of these elements itself information.

Data Descriptor

Look at this example:

var chris = {};
Object.defineProperty(chris, "IQ", {
    value: 228,
    writable: false,
    configurable: true,
    enumerable: true
});
chris.IQ = 61; // 静默失败了,如果是严格模式则会 TypeError
chris.IQ; // 228

By definePropertybe configured attribute descriptor (meta information) corresponding to the properties of an object, and the access attribute descriptor contains data descriptor and the descriptor, the above example, definePropertythe third parameter definition data of several data descriptor, which writablerepresents write, configurableindicating whether attributes configurable (note, not the configuration is modified to one-way operation), enumerableit indicates whether the attribute should appear in the enumeration, such as for..inthe.

Obviously we can protect the descriptors property by property, but there are also some handy functions to do similar things. As Object.preventExtensions()will retain properties but prevent new attributes Object.seal()will be sealed, on the basis of the property is prohibited to add new attribute marked as not original configuration, Object.freeze()it will freeze the object, i.e., the attribute flag data access on the basis of the seal is not write.

[[Get]], [[Put]]And Access Descriptor

When we visited and valued property of an object, in fact, by [[Get]]and [[Put]]operate, for example, property access, [[Get]]will go first to have this property, if no object will traverse the [[Prototype]]chain (chain prototype, this time to talk about this concept) come, we can not find the return undefined. And this behavior is actually allowed us to set getter ( ) get()and setter ( ) set()function to change, they are called Access Descriptor .

When we provide access descriptors corresponding access operations are no longer affected by the value of the property and writable, the other should be noted that, although they are also the property descriptor, but defines getter and setter are not required by law to pass definePropertysettings:

var obj = {
    get a() { // 给 a 属性定义 getter
        return this._a_;
    },
    set a(val) { // a 属性的 setter
        this._a_ = val * 2;
    }
}

obj.a = 2;
obj.a; // 4

The existence of property

Because the value of the property may be undefined, there is no direct access to the properties obtained also undefined, so direct access is through a simple attribute can not distinguish whether there is, then we can pass inor hasOwnProperty()check whether an object exists in the property:

var obj = {a : 2};
"a" in obj; // true
obj.hasOwnProperty("a"); // true

Although the concept of the prototype chain is still not mentioned here it should still be noted that inoperators will check whether there is property in the prototype chain, but hasOwnPropertydoes not. In addition, in some cases, some objects will not have hasOwnPropertythis property (here not to mention the reason), then can be used Object.prototype.hasOwnProperty.call(objName, propertyName)to carry out the inspection.

At last

Following the last time thisthe conduct of research, this time to learn more about the basic concepts in JavaScript object properties. As before, if you want to learn more about this relevant content, you may wish to read "You do not know JS - this & object prototypes" a book (this covers only a chapter of the book "Object" ). This is an open book, you can read the book online here or buy the book in electronic or print edition. The Chinese translation of the book covers in "you do not know JavaScript on a roll." You can see consider the Chinese version.

Finally, although I will check the content of the article as carefully as if there are problems, but this article does not guarantee there will not be wrong, if you find the article where there are problems, please correct me in the comments below, or by anything you find the correct way to contact me. Grateful ~

Guess you like

Origin www.cnblogs.com/blumia/p/Thats-JavaScript-object-property.html