Home > Web Front-end > JS Tutorial > Learn more about JavaScript objects_javascript skills

Learn more about JavaScript objects_javascript skills

WBOY
Release: 2016-05-16 15:36:51
Original
948 people have browsed it

In JavaScript, except for the five primitive types (i.e., numbers, strings, Boolean values, null, and undefined), they are all objects. So, how can you continue to learn if you don’t understand objects?

1. Overview

An object is a composite value that aggregates many values ​​(primitive values ​​or other objects) together, which can be accessed through property names. The attribute name can be any string including the empty string. JavaScript objects can also be called a data structure, as we often hear about "hash", "hashtable", "dictionary", and "associative array".

Objects in JavaScript can be divided into three categories:

①Built-in objects, such as arrays, functions, dates, etc.;

②The host object is defined by the host environment (such as the browser) in which the JavaScript interpreter is embedded, such as HTMLElement, etc.;

③ Custom objects, which are defined by programmers in code;

The properties of objects can be divided into two categories:

①Own property: Properties defined directly in the object;

②Inherited property: Properties defined in the object’s prototype object (the prototype object will be discussed in detail below);

2. Creation of objects

Since you are learning objects, how can you not understand how to create objects? Students who are interviewing for front-end positions may have been asked this basic question:

What are the two ways to create JavaScript objects? (Or: tell me how to create JavaScript objects?)

I have been asked this question twice. There are many sayings on the Internet about "two ways to create objects", but according to the books I have read, there are three ways! Let’s talk about these three methods in detail below:

1. Object direct quantity

The object literal is a mapping table composed of several name/value pairs. The name/value pairs are separated by colons, the name/value pairs are separated by commas, and the entire mapping table is enclosed in curly braces. The attribute name can be a JavaScript identifier or a string literal. That is to say, the following two ways of writing the object obj are exactly the same:

var obj = {x: 1, y: 2};
var obj = {'x': 1, 'y':2};

2. Create objects through new

The new operator is followed by a function call, the constructor, which creates and initializes a new object. For example:

1 var o = new Object(); //Create an empty object, the same as {}
2 var a = new Array(); //Create an empty array, the same as []
3 var d = new Date(); //Create a Date object representing the current time

We will talk about the constructor-related content later.

3.Object.create()

ECMAScript5 defines a method called Object.create(), which creates a new object. The first parameter is the prototype object of this object (it seems that the prototype object has not been explained yet... I will talk about it soon), and the second parameter is the prototype object of this object. An optional parameter is used to further describe the properties of the object. The second parameter will be discussed below (because this third method is defined in ECMAScript5, so everyone often talked about the two methods of creating objects in the past, right? Personally I think this is the reason). This method is very simple to use:

1 var o1 = Object.create({x: 1, y: 2}); //Object o1 inherits the attributes x and y
2 var o2 = Object.create(null); //Object o2 has no prototype

The following three are exactly the same:

1 var obj1 = {};
2 var obj2 = new Object();
3 var obj3 = Object.create(Object.prototype);

In order to explain why these three methods are exactly the same, let’s first explain the prototype object in JavaScript (oh, I kept you waiting for a long time!). I remember a great god said:

Javascript is an object-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because there is no class in its syntax.

Object-oriented programming language JavaScript, no classes! ! ! So, how does it implement inheritance? That's right, through the prototype object. Basically every JavaScript object (except null) is associated with another object. The "other" object is the so-called prototype object (the prototype object can also be referred to as the prototype for short. It is not as complicated as imagined, it is just an object. ). Every object inherits properties from the prototype object, and the value of the prototype property of an object (this property is automatically generated by default when the object is created and does not require explicit customization) is the prototype object of the object, that is, obj.prototype is the object. The prototype object of obj.

Let’s talk about prototype objects first. Returning to the above question, with the understanding of prototype objects, the following are the JavaScript language regulations that do not require too much explanation:

①The prototype object of all objects created through object literals is the Object.prototype object;

②The prototype object of the object created through the keyword new and the constructor function is the value of the prototype attribute of the constructor function, so the prototype of the object created through the constructor function Object is Object.prototype;

The meaning of the first parameter of the third method of creating objects, Object.create(), is now also added.

3. Attribute query and setting

Learning how to create objects is not enough, because objects can only really play a role if they have some properties! So, let’s continue to learn the properties of objects!

The value of an attribute can be obtained and set using the dot (.) or square bracket ([]) operators. For the dot (.), the right side must be an identifier named after the attribute name (note: JavaScript language identifiers have their own legal rules and are different from quoted strings); for square brackets ([] ), the square brackets must be a string expression (of course string variables can also be used, and other values ​​that can be converted into strings, such as numbers, etc.), and this string is the name of the attribute. Just like the following example:

var obj = {x: 1, y: 2}; 
obj.x = 5; 
obj['y'] = 6 
Copy after login

As mentioned in the overview, JavaScript objects have "own properties" and "inherited properties". When querying the attribute Whether the prototype object obj.prototype.prototype of .prototype has attribute x, this is until x is found or the prototype object found is an undefined object. As you can see, an object inherits many prototype objects, and these prototype objects form a "chain". This is what we usually call the "prototype chain". This kind of inheritance is also the "prototypal inheritance" in JavaScript ( prototypal inheritance).

When object o queries a certain attribute, it will search step by step along the prototype chain as mentioned above, but when it sets the value of a certain attribute, it will only modify its own attributes (if the object does not have this attribute, it will be added This property and assigning a value) will not modify the properties of other objects on the prototype chain.

4. Accessor attribute getter and setter

What we talked about above are very common object properties. This kind of property is called "data property", and the data property has only one simple value. However, in ECMAScript 5, property values ​​can be replaced by one or two methods. These two methods are getters and setters. Properties defined by getters and setters are called "accessor properties".

When a program queries the value of an accessor property, JavaScript calls the getter method (without parameters). The return value of this method is the value of the attribute access expression. When a program sets the value of an accessor property, JavaScript calls the setter method, passing the value on the right side of the assignment expression as a parameter to the setter. If a property has both getter and setter methods, then it is a read/write property; if it only has a getter method, then it is a read-only property. Assigning a value to a read-only property will not report an error, but it will not succeed; if it only has a setter, method, then it is a write-only property, and reading a write-only property always returns undefined. Let’s look at a practical example:

var p = { 
  x: 1.0, 
  y: 2.0, 
  get r(){ return Math.sqrt(this.x*this.x + this.y*this.y); }; 
  set r(newvalue){ 
    var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y); 
    var ratio = newvalue/oldvalue; 
    this.x *= ratio; 
    this.y *= ratio; 
  }, 
  get theta(){ return Math.atan2(this.y, this.x); }, 
print: function(){ console.log('x:'+this.x+', y:'+this.y); } 
}; 
Copy after login

As written in the example, the accessor attribute defines one or two functions with the same name as the attribute. This function definition does not use the function keyword, but uses get and set, and does not use a colon to separate the attribute name from the function body. separated. For comparison, the print attribute below is a function method. Note: The usage of this keyword in getter and setter here, JavaScript calls these functions as methods of objects, that is, this in the function body points to this object. Let’s take a look at the results of the example operation:

Just like the console output, r and theta are just value attributes like x and y, and print is a method attribute.

The accessor added in ECMAScript 5, although more complex than ordinary attributes, also makes the key-value pairs of the operating object attributes more rigorous.

5. Delete attributes

Programmers generally implement the functions of adding, deleting, modifying, and checking when coding. We have already mentioned adding, modifying, and checking before. Now let’s talk about deletion!

The delete operator can delete the properties of an object, and its operand should be a property access expression. However, delete only disconnects the attribute from the host object, but does not operate the attributes in the attribute:

var a = {p:{x:1}}; 
var b = a.p; 
delete a.p; 
Copy after login

执行这段代码后b.x的值依然是1,由于已删除属性的引用依然存在,所以有时这种不严谨的代码会造成内存泄露,所以在销毁对象的时候,要遍历属性中的属性,依次删除。

delete表达式返回true的情况:

①删除成功或没有任何副作用(比如删除不存在的属性)时;

②如果delete后不是一个属性访问表达式;

var obj = {x: 1,get r(){return 5;},set r(newvalue){this.x = newvalue;}}; 
delete obj.x;  //删除对象obj的属性x,返回true 
delete obj.x;  //删除不存在的属性,返回true 
delete obj.r;  //删除对象obj的属性r,返回true 
delete obj.toString;  //没有任何副作用(toString是继承来的,并不能删除),返回true 
delete 1;  //数字1不是属性访问表达式,返回true 
Copy after login

delete表达式返回false的情况:

①删除可配置性(可配置性是属性的一种特性,下面会谈到)为false的属性时;

delete Object.prototype; //返回false,prototype属性是不可配置的
//通过var声明的变量或function声明的函数是全局对象的不可配置属性
var x = 1;
delete this.x; //返回false
function f() {}
delete this.f; //返回false

六.属性的特性

上面已经说到了属性的可配置性特性,因为下面要说的检测属性和枚举属性还要用到属性的特性这些概念,所以现在就先具体说说属性的特性吧!

除了包含名字和值之外,属性还包含一些标识它们可写、可枚举、可配置的三种特性。在ECMAScript 3中无法设置这些特性,所有通过ECMAScript 3的程序创建的属性都是可写的、可枚举的和可配置的,且无法对这些特性做修改。ECMAScript 5中提供了查询和设置这些属性特性的API。这些API对于库的开发者非常有用,因为:

①可以通过这些API给原型对象添加方法,并将它们设置成不可枚举的,这让它们更像内置方法;

②可以通过这些API给对象定义不能修改或删除的属性,借此“锁定”这个对象;

在这里我们将存取器属性的getter和setter方法看成是属性的特性。按照这个逻辑,我们也可以把属性的值同样看做属性的特性。因此,可以认 为属性包含一个名字和4个特性。数据属性的4个特性分别是它的值(value)、可写性(writable)、可枚举性(enumerable)和可配置 性(configurable)。存取器属性不具有值特性和可写性它们的可写性是由setter方法是否存在与否决定的。因此存取器属性的4个特性是读取 (get)、写入(set)、可枚举性和可配置性。

为了实现属性特性的查询和设置操作,ECMAScript 5中定义了一个名为“属性描述符”(property descriptor)的对象,这个对象代表那4个特性。描述符对象的属性和它们所描述的属性特性是同名的。因此,数据属性的描述符对象的属性有 value、writable、enumerable和configurable。存取器属性的描述符对象则用get属性和set属性代替value和 writable。其中writable、enumerable和configurable都是布尔值,当然,get属性和set属性是函数值。通过调用 Object.getOwnPropertyDescriptor()可以获得某个对象特定属性的属性描述符:

从函数名字就可以看出,Object.getOwnPropertyDescriptor()只能得到自有属性的描述符,对于继承属性和不存在的属性它都返回undefined。要想获得继承属性的特性,需要遍历原型链(不会遍历原型链?不要急,下面会说到的)。

要想设置属性的特性,或者想让新建属性具有某种特性,则需要调用Object.definePeoperty(),传入需要修改的对象、要创建或修改的属性的名称以及属性描述符对象:

可以看到:

①传入Object.defineProperty()的属性描述符对象不必包含所有4个特性;

②可写性控制着对属性值的修改;

③可枚举性控制着属性是否可枚举(枚举属性,下面会说的);

④可配置性控制着对其他特性(包括前面说过的属性是否可以删除)的修改;

如果要同时修改或创建多个属性,则需要使用Object.defineProperties()。第一个参数是要修改的对象,第二个参数是一个映射表,它包含要新建或修改的属性的名称,以及它们的属性描述符,例如:

var p = Object.defineProperties({},{ 
  x: {value: 1, writable: true, enumerable: true, configurable: true}, 
  y: {value: 2, writable: true, enumerable: true, configurable: true}, 
  r: {get: function(){return 88;}, set: function(newvalue){this.x =newvalue;},enumerable: true, configurable: true}, 
  greet: {value: function(){console.log('hello,world');}, writable: true, enumerable: true, configurable: true} 
}); 
Copy after login

相信你也已经从实例中看出:Object.defineProperty()和Object.defineProperties()都返回修改后的对象。

前面我们说getter和setter存取器属性时使用对象直接量语法给新对象定义存取器属性,但并不能查询属性的getter和setter方法 或给已有的对象添加新的存取器属性。在ECMAScript 5中,就可以通过Object.getOwnPropertyDescriptor()和Object.defineProperty()来完成这些工作 啦!但在ECMAScript 5之前,大多数浏览器(IE除外啦)已经支持对象直接量语法中的get和set写法了。所以这些浏览器还提供了非标准的老式API用来查询和设置 getter和setter。这些API有4个方法组成,所有对象都拥有这些方法。__lookupGetter__()和 __lookupSetter__()用以返回一个命名属性的getter和setter方法。__defineGetter__()和 __defineSetter__()用以定义getter和setter。这四个方法都是以两条下划线做前缀,两条下划线做后缀,以表明它们是非标准方 法。下面是它们用法:

七.检测属性

JavaScript对象可以看做属性的集合,那么我们有时就需要判断某个属性是否存在于某个对象中,这就是接下来要说的检测属性。

检测一个对象的属性也有三种方法,下面就来详细说说它们的作用及区别!

1.in运算符

in运算符左侧是属性名(字符串),右侧是对象。如果对象的自有属性或继承属性中包含这个属性则返回true,否则返回false。

为了试验,我们先给对象Object.prototype添加一个可枚举属性m,一个不可枚举属性n;然后,给对象obj定义两个可枚举属性x,一个不可枚举属性y,并且对象obj是通过对象直接量形式创建的,继承了Object.prototype。下面看实例:

从运行结果可以看出:in运算符左侧是属性名(字符串),右侧是对象。如果对象的自有属性或继承属性(不论这些属性是否可枚举)中包含这个属性则返回true,否则返回false。

2.hasOwnProperty()

对象的hasOwnProperty()方法用来检测给定的名字是否是对象的自有属性(不论这些属性是否可枚举),对于继承属性它将返回false。下面看实例:

3.propertyIsEnumerable()

propertyIsEnumerable()是hasOwnProperty()的增强版,只有检测到是自有属性且这个属性可枚举性为true时它才返回true。还是实例:

八.枚举属性

相对于检测属性,我们更常用的是枚举属性。枚举属性我们通常使用for/in循环,它可以在循环体中遍历对象中所有可枚举的自有属性和继承属性,把属性名称赋值给循环变量。继续上实例:

我原来认为for/in循环跟in运算符有莫大关系的,现在看来它们的规则并不相同啊!当然,如果这里不想遍历出继承的属性,那就在for/in循环中加一层hasOwnProperty()判断:

for(prop in obj){ 
  if(obj.hasOwnProperty(prop)){ 
    console.log(prop); 
  } 
} 
Copy after login

除了for/in循环之外,ECMAScript 5还定义了两个可以枚举属性名称的函数:

①Object.getOwnpropertyNames(),它返回对象的所有自有属性的名称,不论是否可枚举;

②Object.keys(),它返回对象对象中可枚举的自有属性的名称;

还是实例:

九.对象的三个特殊属性

每个对象都有与之相关的原型(prototype)、类(class)和可扩展性(extensible attribute)。这三个就是对象的特殊属性(它们也只是对象的属性而已,并没有想象的复杂哦)。

1.原型属性

正如前面所说,对象的原型属性是用来继承属性的(有点绕…),这个属性如此重要,以至于我们经常把“o的原型属性”直接叫做“o的原型”。原型属性 是在实例创建之初就设置好的(也就是说,这个属性的值是JavaScript默认自动设置的,后面我们会说如何自己手动设置),前面也提到:

①通过对象直接量创建的对象使用Object.prototype作为它们的原型;

②通过new+构造函数创建的对象使用构造函数的prototype属性作为它们的原型;

③通过Object.create()创建的对象使用第一个参数(如果这个参数为null,则对象原型属性值为undefined;如果这个参数为 undefined,则会报错:Uncaught TypeError: Object prototype may only be an Object or null: undefined)作为它们的原型;

那么,如何查询一个对象的原型属性呢?在ECMAScript 5中,将对象作为参数传入Object.getPrototypeOf()可以查询它的原型,例如:

但是在ECMAScript 3中,没有Object.getPrototypeOf()函数,但经常使用表达式obj.constructor.prototype来检测一个对象的原型,因为每个对象都有一个constructor属性表示这个对象的构造函数:

①通过对象直接量创建的对象的constructor属性指向构造函数Object();

②通过new+构造函数创建的对象的constructor属性指向构造函数;

③通过Object.create()创建的对象的constructor属性指向与其原型对象的constructor属性指向相同;

要检测一个对象是否是另一个对象的原型(或处于原型链中),可以使用isPrototypeOf()方法。例如:

还有一个非标准但众多浏览器都已实现的对象的属性__proto__(同样是两个下划线开始和结束,以表明其为非标准),用以直接查询/设置对象的原型。

2.类属性

对象的类属性(class attribute)是一个字符串,用以表示对象的类型信息。ECMAScript 3 和ECMAScript 5 都未提供设置这个属性的方法,并只有一种间接的方法可以查询它。默认的toString()方法(继承自Object.prototype)返回了这种格 式的字符串:[object class] 。因此,要想获得对象的类,可以调用对象的toString()方法,然后提取已返回字符串的第8到倒数第二个位置之间的字符。不过,很多对象继承的 toString()方法重写了(比如:Array、Date等),为了能调用正确的toString()版本,必须间接地调用 Function.call()方法。下面代码可以返回传递给它的任意对象的类:

function classof(obj){
  if(o === null){
    return 'Null';
  }
  if(o === undefined){
    return 'Undefined';
  }
  return Object.prototype.toString.call(o).slice(8, -1);
}

Copy after login

The classof() function can pass in any type of parameters. Here are usage examples:

Summary: It can be seen from the running results that the class attributes of the objects created in the three ways are all 'Object'.

3. Scalability

The extensibility of an object indicates whether new properties can be added to the object. All built-in and custom objects are explicitly extensible (unless they are converted to non-extensible). The extensibility of host objects is defined by the JavaScript engine. ECMAScript 5 defines functions for querying and setting the scalability of objects:

① (Query) Determine whether the object is extensible by passing the object into Object.isExtensible().

② (Settings) If you want to convert the object to non-extensible, you need to call Object.preventExtensions() and pass the object to be converted as a parameter. Note:

a. Once an object is converted to non-extensible, it cannot be converted back to extensible;

b.preventExtensions() only affects the extensibility of the object itself. If you add properties to the prototype of a non-extensible object, the non-extensible object will also inherit these new properties;

Furthermore, Object.seal() is similar to Object.preventExtensions(). In addition to setting the object to be non-extensible, you can also set all of the object's own properties to be non-configurable. Objects that have been sealed cannot be unsealed. You can use Object.isSealed() to detect whether an object is sealed.

Going a step further, Object.freeze() will lock the object more strictly - "frozen". In addition to making an object non-extensible and its properties non-configurable, you can also set all of its own data properties to read-only (if the object's accessor properties have setter methods, the accessor properties will not Affected, they can still be called by assigning values ​​to properties). Use Object.isFrozen() to detect whether an object is frozen.

Summary: Object.preventExtensions(), Object.seal() and Object.freeze() all return the passed in object, that is, they can be called in a nested manner:

var obj = Object.seal(Object.create(Object.freeze({x:1}),{y:{value: 2, writable: true}));

This statement uses the Object.create() function to pass in two parameters, that is, the first parameter is the prototype object of the created object, and the second parameter is the attribute defined directly for the object when it is created. , and comes with defined attributes.

10. Serialization of objects

After talking about the properties of objects and the characteristics of object properties, there are still quite a lot of things. I don’t know if you are confused. However, the following is a more relaxed topic!

Object serialization refers to converting the state of an object into a string, and can also restore a string to an object. ECMAScript 5 provides built-in functions JSON.stringify() and JSON.parse() for serializing and restoring objects. These methods all use JSON as the data exchange format. The full name of JSON is "JavaScript Object Notation" - JavaScript object notation. Its syntax is very similar to the syntax of JavaScript objects and array direct quantities:

Among them, the last jsonObj is a deep copy of obj

The syntax of JSON is a subset of JavaScript, and it cannot represent all values ​​in JavaScript. Objects, arrays, strings, infinite numbers, true, false, and null are supported, and they can be serialized and restored. Note:

①The result of NaN, Infinity and -Infinity serialization is null;

②JSON.stringify() can only serialize the object’s own enumerable properties;

③The result of serialization of date objects is date strings in ISO format (refer to Date.toJSON() function), but JSON.parse() still retains their string form and cannot restore them to the original date objects. ;

④Functions, RegExp, Error objects and undefined values ​​cannot be serialized and restored;

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

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