JavaScript basic (4) - all-inclusive object (under)

  Learn the previous chapter major additions and deletions to change search object, leads to the concept and prototype inheritance chain, in this chapter we have a good talk to the object's properties, some of the more useful methods and properties in the properties of the object, to understand these methods you could write code does not help, but if you want to package a large, easy to use object - such as Vue, you may need to use a number of tools inside.

1. Detection Properties

Sometimes we need to detect whether an object contains a property, this time we can in operators, hasOwnPreperty () or propertyIsEnumerable () method to do this, of course, you can also point (.) Or square brackets ([ ]) operator query to do this. We adopted the following simple code to detect these types of review under way.

let o = {x:1}
o.y === undefined // true 最简单的属性查询方式
'x' in o // true 注意要用引号把属性值包起来
'toString' in o // true in运算符可以查询到继承属性
o.toString() // '[Object Object]' 直接查询也可以查询到继承属性

o.hasOwnProperty('toString') 
// false hasOwnProperty用来检测对象的自有属性,对于继承属性返回false

o.propertyIsEnumerable('toString') 
// false propertyIsEnumerable是hasOwnProperty的增强版
// 只有检测到可枚举型的自有属性为true时返回true。通常由JavaScript创建的对象默认是可枚举的。

  Note needs, hasOwnProperty () method can only detect its own properties of an object, it looks like a bit tasteless, but this method is very useful in some cases, when a very large object inherits from a parent object, which property values ​​you might not have inherited entirely clear, this time you want to access a property of the object do not want to suffer when a parent object can be detected interference of its own properties of the object using this method. About propertyIsEnumerble approach became apparent, the detection method is not only the property owned property, it had to be enumerable, on enumerable property we will be described later.

2. enumerated attribute

  In addition to detecting whether the object exists, we also need to detect whether the object is enumerable. When we use for / in loop through when the properties of an object, not only can traverse own properties of an object, you can also traverse the object inherits the properties we use for / in time basically only traverse to the property you want, Description Object.prototype inside of the properties are not enumerable, this need to look at, the following look at an example to demonstrate at for / in not only their own property may also traverse traverse inherit property.

// 继承 这个方法在上一章已经写过,这里再回顾一下
function inherit(p){
    if(p===null){
		throw TypeError()
	}
	if(Object.create){
		return Object.create(p)
	}
	if(typeof(p)!=='object'&&typeof(p)!=='function'){
		throw TypeError()
	}
	function fn(){}
	fn.prototype = p
	return new fn()
}

let o = {x:1}
let p = inherit(o)
p.y = 2
for(let key in p){
	console.log(key) //第一次是自有属性y,第二次是继承的可枚举属性x
}

  As the for / in loop to iterate sometimes some properties (such as certain vegetables from forced write constructor inherited some of the enumerable properties) we do not want, so we need to filter these properties get what we want own property. In fact Object.keys ES5 provided () method has helped us to filter the inherited enumerable properties to achieve the idea is as follows

Object.prototype.keys= function(o){
  if(typeof(o)!=='object') {throw TypeError()}
  let	arr = [] //用与存储key值
	for(let prop in o){
		if(o.hasOwnProperty(prop)){
			arr.push(prop)
		}
	}
	return arr
}

let o = {x:1}
let p = inherit(o)
p.y = 2
Object.keys(p) // ['y']

3. Properties listener getter and setter

  We all know that the core Vue two-way data binding is to rewrite object attributes get and set methods, you can use one or both methods instead ES5 species, the property value, which is two getter and setter methods, defined by getter and setter of property known as "memory attribute" personally, I prefer to call him "the monitored property", as with "memory property," the official statement, the common property we call data attributes.

  When the program queries a "monitored Properties" ( behind the official statement being monitored property instead of memory attributes I will ) when, JavaScript calls will go getter method of the property, note that this method is no argument, this method returns value is the value of the property being monitored. When the value of the program settings (overwrite) a monitored attribute, JavaScript will call the setter method of the property and the value of the right side of an assignment expression passed as a parameter setter.

  Behavior when All in all, the properties can be monitored human rewrite read and set properties so that we can attribute properties and related operations and do whatever it pleases in reading and setting properties of time , with these two methods, we can monitor real-time changes in data and read. If a property has both a getter and setter methods, then he has a read / write property, if he only getter method, then he is a read-only attribute, if he only setter method, then he is a write-only attribute to read write-only property always returns undefined.

  Having said that, let's simply use under the property getter and setter methods do whatever they want in the operation of some

var rect = {
	'width':3,
	'height':4,
	// 读取对角线
	get diagonal(){
		return Math.sqrt(this.width*this.width + this.height*this.height)
	},
	// 改对角线
	set diagonal(newVal){
		var oldVal = Math.sqrt(this.width*this.width + this.height*this.height)
		var ratio = newVal/oldVal
		this.width *= ratio
		this.height *= ratio
	},
	// theta只读
	get theta(){return Math.atan2(this.height,this.width)}
}
rect.diagonal // 5
rect.diagonal = 10
rect.width //6
rect.height //8

  The code above this key point in the current object, you only need to know that you can, and when we visit diagonal property returns is to calculate the value of an expression, when we rewrite the diagonal when he's width and height information will make the appropriate changes. Listening through the property getter and setter methods for data have practical applications in many scenarios, but here introduce more (because the content of this chapter is really a bit much!)

4. The characteristic properties of the three

  In addition to the key attributes of the object and value, whether they also contain writable, enumerable and configurable features some of the logo, you can also call the three major state value of the property. These characteristic values ​​are present in all of the properties, but only through a special set of API to learn the API for the development of business does not help, but if you want to develop an API library, these methods it is particularly important.

  We will remember for / in the enumeration property when inheriting property is for / circulation problems in the print out of it? You certainly can not expect to use your API tools to build the user also knows how to use hasOwnProperty () it, so you will need these may be inherited properties and methods of non-enumerable set, which can make them look more like a built-in method. You can also set the property of an object can not write to lock the value of the property.

  JavaScript property of the value of the data (value) and be monitored properties get, set method as a characteristic property of order dividing them into

  Four characteristic data attribute: value (value), writability (writable), can be enumerated type (Enumerable) and configurability (Configurable)

  Due to the property being monitored by the reading and writing of the decision and get set.

  Property being monitored four features: readability (get), writability (set), the enumerable type (enumerable) and configurable (configurable)

  Introduced over the characteristics of the property, then the JavaScript API which provides features to manipulate the properties of it? First ES5 defines an object called "property descriptor" for querying property descriptor for an attribute of an object, you can query by calling Object.getOwnPropertyDescriptor (obj, key).

Object.getOwnPropertyDescriptor({x:1},'x')
//{value: 1, writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor(rect,'diagonal')
//{get: ƒ, set: ƒ, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor({x:1},'toString')
//undefined

  Note that, Object.getOwnPropertyDescriptor () method can only get its own property descriptor, you want to get properties inherited property, you need to traverse the prototype chain, which will be mentioned later how to achieve.

  Having the characteristics of how to query attributes, let us talk about how to set the properties property. Call Object.defineProperty () to set a property of the object can be achieved. Let's look at a simple example:

let o = {}
Object.defineProperty(o,'x',{
	value:1,
	writable:true,
	enumerable:false, //设置x属性不可枚举
	configurable:true
})
o.x // 1
Object.keys(o) // [] x属性不可枚举

//下面我们对属性x做修改,让他变为只读属性
Object.defineProperty(o,'x',{writable:false})

//试图修改这个属性的值
o.x = 2 //操作失败但不报错,严格模式下会抛出类型错误异常
o.x //1

  In the above example, we set the x property is not available and can not be written to enumerate, we is not no way to modify the value of x na? Not! As the x property still is configurable, we can call Object.defineProperty modify his method of reading value. Methods as below

Object.defineProperty(o,'x',{value:2})
o.x //2

  Can be seen from the above wording, incoming Object.defineProperty attribute descriptor object does not necessarily contain all four features. Also need to pay attention to a point, this method can only modify or create new own property, can not be operated inherited properties.

  If you need to modify or create a plurality of attributes, we can use Object.defineProperties (), the first parameter is an object to be modified, the second parameter is a mapping table, for example:

var p = Object.defineProperties({},{
    x:{value:1,writable:true,enumerable:true,confitable:true},
    y:{value:2,writable:true,enumerable:true,confitable:true}
    ...
})

 

  This chapter describes some of the operations an object property, on three properties of the object (prototype, types, scalability), can find out, on an object method, commonly used object serialization operation may look, chapter time then I will mend the prototype property of the object, other content will not say more, say no good, you can point interested followers can also be assigned to individual fan base 708 637 831

 

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

Guess you like

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