JavaScript basic (3) - encompassing objects (on)

 The third article in this series to skip the contents of Chapters IV and V "JavaScript The Definitive Guide," the (personally feel that these two chapters introduce bias and content to the dictionary), directly to a chat in the most complex JavaScript, It is the most important basic data types - objects.

1. What is the subject?

  Object: especially love each other, referring to male, girlfriend relationship, both sides love to call behavior, thinking fart eat?

  JavaScript object refers to all the values ​​except strings, numbers, Boolean values, null, and undefined.

  When determining the type of data, we tend to help the keyword typeof, as follows:

typeof(1) //number
typeof(undefined) //undefined
typeof('undefined') //string
typeof(true) //boolean

 However, we can not just typeof to determine whether a value object, as follows:

typeof({}) //object
typeof(null) //object
typeof(function a(){}) //function

 So sometimes we need to use a "traditional object" as a parameter, it is necessary to filter out null, at the same time, we do not need to worry about users will pass a function object, because the function object will be directly filtered into typeof function.

//判断一个值是否为对象
function isObject(o){
  return typeof(o)==='object'&&o!==null
}
isObject({}) //true
isObject(null) //false
isObject(1) //false

  From a narrow angle, the object is one of the six JavaScript data types (ES6 added a symbol type, this article does not discuss) , but in the actual development scenario, the object but has a broader application.

  In the second chapter of this series, I introduced the concept of "wrapper object", namely strings, numbers, Boolean type in the actual usage scenarios, will be showing a characteristic of an object, they behave like a special "not change object ", based on this characteristic, we can draw the following conclusions:

  In addition to null and undefined, all data types have characteristics of the object.

2. Object of three ways to create ways

  The easiest way to create an object is to use the code in the amount of JavaScript code directly, of course, you can also create an instance of the constructor keyword new, in addition, there is a more popular method, you can call built-in Object.create () function to create objects. Three ways to create objects shown as follows:

// 代码直接量
var point = {x:1}
// new关键字
var empty= new Object() // {}
// Object.create()
var rect= Object.create({width:3,height:4}) // rect继承了width和height

  Note that, a new object is created and initialized by the new operator, requires a corresponding constructor, as Date, Array, Object systems which are built constructor can be called directly. Details of the constructor, but more discussion paper (because I have not seen so and so after reading the talk).

  About Object.create (), I was particularly marked comments. ES5 defined Object.create () method, you can create a new object, where the first parameter is the prototype of this object, we need to print it out, to see his particularity.

  As shown above, the new object Object.create () created (assuming that variable named letter o) itself does not "x" property, but we can still have access to the ox = 1, this is because o Although the property does not have x, but the x property on his prototype chain, so when we asked ox side, the result returned is the prototype of the first chain o find the x property (if property x readable words).

  Said a long time, foggy do not know spade, we again re-processing logic, by Object.create (), to manage the concept of a physical prototype chain.

 3. By the Object.create () to understand prototype chain

  Online concerning the concept of prototype and prototype chain has a lot of, here we pass Object.create () to draw an analogy:

  Object.create () is a lawyer law firm, he is dedicated to the management of property inheritance

  One day, a father (father), his name has {car: 10, real estate ': 5 sets, the company: 2}, came to the law firm Object, find a lawyer create, father (father), want to his property to his adoptive son (son).

So we get the following equation: son = Object.create (father).

Q: What property, the property of his father and what his son have now?

A:. Son car = 10, son of real estate = 5 sets, son company = 2, father car = 10, father Property = 5 sets, father company = 2.....

Some say he Bu believe we seeing is believing:

Some people think that to get away? Do not! The truth is far from that simple.

  shock! Hangzhou, a guy inherited his father ten million property, but can afford millions of diamonds, the answer turned out to be his grandfather is Ma!

  In fact, the above example is the concept of object prototype chain, although the son is in itself a pauper, but to ask his property, he would follow up genealogy to find until you find the "nearest" of the property, he will tell you he there are 5 sets (father's) property, we assume that the father also inherited his grandfather 100 sets of real estate, then the son will how to answer it? The answer is: 5 sets! Because once the corresponding attribute is found, the query object will not continue deeply.

  Having a story, we return to the concept of prototype and prototype chains, all JavaScript objects (except null) are with another object "associated with" another object is, we know the prototype, each object from prototype to inherit property, and a prototype, It will inherit properties from the prototype of the prototype, thus forming a "prototype chain", then this prototype chain when it terminated? I would have to mention the Object.prototype.

  Object.prototype is one of the few not the prototype object, he did not inherit any property, all of the constructors have built a prototype inherited from Object.prototype, by all objects created with a direct and have the same prototype object Object .prototype. Therefore, we can create a common space objects through Object.create (Object.prototype).

  By prototypal inheritance method, we can obtain a new object inherits from the prototype, this method is very useful when operating object code is as follows:

// 对象继承
function inherit(p){
    if(p===null){throw TypeError()}
	if(Object.create){
		return Object.create(p)
	}
	// 如果浏览器不支持Object.create
	if(typeof(p)!=="object"&&typeof(p)!=="function"){throw TypeError()}
	function fn(){} //创建构造函数
	fn.prototype = p //构造函数原型继承p
	return new fn() //返回一个继承了父对象的子实例
}

   The actual operation can not be too much trouble to use inheritance function, you can prototype inheritance by o = Object.create (p).

Property queries with "Short Circuit" 4 object

  We may by square brackets may be the point (.) Or brackets ([]) operator to get the value of the attribute for the point (.), It must be simple right identifier to a name attribute named It is a simple identifier, or may be a calculated value. When setting properties, try not to use reserved words (ES3 not supported).

  We often need to use brackets ([]) operator to help us to obtain a dynamic query and set properties, as follows

let json = {}
for(let i=0;i<10;i++){
	json[i] = '属性'+ i
}
console.log(json) //{0:'属性0','1':'属性1' ....}

  Live attribute access does not always return a value set, if the query a nonexistent property, JavaScript and does not complain, but returns undefined, but if you want to query an object does not exist, JavaScript must the error.

 O There are objects such as a property {x: 1}, then you want to look up, oy, because the prototype chain on its own property and are not x y, so this expression returns an undefined, but if you want to check oyz , JavaScript will not put up with that, because you want to look up is a x.undefined.z, in this case, JavaScript will throw an exception of a type error.

  In a real project, we often encounter this situation, in some cases as o.arr established, then o.arr some cases = undefined, then we will throw a visit o.arr.length system the type of error exception to resolve this uncertainty of the optimal solution is to use a short-circuit behavior && operator.

 We can access o.arr && o.arr.length, because the operator only return "and" In the case of all expressions are true will be true, so once checked into one of these expressions is false, he directly returns false, it does not continue behind the statement, which avoids accessing undefined attributes.

5. In-depth understanding of inherited objects

  JavaScript object has its own properties, such as o = {x: 1}, you visit OX, o is the own access attributes x, and you can use o.toString () method, toString is inherited from the inside Object.prototype Attributes. So when you query an object's properties, he will give priority to its own query the object's properties, and is the prototype of the object, then the prototype is a prototype, the query will encounter a prototype of an object is null terminated, also means with no property you want to find on this object, the system will return an undefined. We can see the prototype property of the object constitutes a "chain query" through the chain on the realization of inherited property.

  The above theory is converted into the code as follows:

let o = {} // 对象直接量创建的时候会继承Object.prototype
o.x = 1 // o拥有一个自有属性x
let p = inherit(o) // p继承了o,也继承了o的原型Object.prototype
p.y = 2 // p拥有一个自有属性y
var q = inherit(p) // q继承了p,也继承了o,也继承了Object.prototype
q.x = 3 // q拥有一个自有属性x,跟o的自有属性同名
q.x + q.y// 5 y继承自p,x是自有属性x

  The above code, since the x property of the same name owned property and inheritance p, x, and thus change the properties in the query time, JavaScript prefers the "first found" properties. Of course, not always the case, where there is a more details

  JavaScript object properties assignment will check the prototype chain, in order to determine whether to allow the assignment.

  In some cases, you may not be able to set up a self-owned property, which is inherited with the property you want to set from a "read only" attribute is related on how to set property attributes, we will discuss in detail in the next section, we change it the above example, look at what happens in this case

let o = {} // 对象直接量创建的时候会继承Object.prototype
// o.x = 1 // o拥有一个自有属性x
Object.defineProperty(o,'x',{value:1,writable:false}) //设置 x属性只读
let p = inherit(o) // p继承了o,也继承了o的原型Object.prototype
p.y = 2 // p拥有一个自有属性y
var q = inherit(p) // q继承了p,也继承了o,也继承了Object.prototype
q.x = 3 // 不能设置该属性
console.log(q.x + q.y)// 3 y继承自p,x继承自o
console.log(q) //{} 自有属性是空

  When we put ox read-only, set qx becomes ineffective, we look at the q looks like your browser to print.

  Of inherited objects can access properties on the prototype chain while not destroy the object on the prototype chain, this feature allows programmers to override the inherited property selective.

6. delete objects

  In fact, many people do not know the properties of the object can be deleted, and we may feel useless property left unattended enough.

  The delete operator can remove the object's properties, his operand should be a property expression. When Note, delete only property off the mat and host objects, and not to operate the property attributes. It sounds very hard to pronounce, we wrote an example look at the know

var a = {p:{x:1}} 
var b = a.p
delele a.p
b.x //1

   Because delete only delete their own property, inherit property can not be deleted, so we need to iterate attribute properties at the time of the destruction of the object attributes, in turn removed to prevent memory leaks. delete non-configurable attributes which can not be deleted, such as Object.prototype, he had been locked up system, if you want to delete Object.prototype, delete the operation returns false.

Published 109 original articles · won praise 196 · Views 300,000 +

Guess you like

Origin blog.csdn.net/dkr380205984/article/details/98183720