ホームページ > 記事 > ウェブフロントエンド > JavaScript学習メモ:オブジェクトの作成_JavaScriptスキル
JavaScript has built-in objects such as Date, Array, String, etc., which are powerful and easy to use, and everyone loves them. However, when dealing with some complex logic, the built-in objects are very powerless, and developers often need to customize objects. .
According to the definition of JavaScript, an object is a collection of unordered properties, and its properties can contain basic values, objects or functions. That is to say, an object is a set of attributes in no particular order. Each attribute is mapped to a value, which is a set of key-value pairs. The value can be data or an object.
Object is the basic data type of JavaScript. In JavaScript, values other than strings, numbers, true, false, null, and undefined are objects. Therefore, it is very difficult to continue learning JavaScript without understanding the objects. Start learning about objects today.
Overview
Object is a basic data type in JavaScript. In terms of data structure, it is a hash table, which can be regarded as an unordered collection of attributes. Everything else is an object except the original value. These values are accessed through the property name, which can be any string including the null character. To put it simply, an object is a collection of attributes. An attribute contains a name (key) and a value (value).
To understand what a JavaScript object is, you can think of it this way. In JavaScript, an object is a specific body with properties. Take the girl you see. This girl is an object. She has her own attributes. For example, the girl’s height, age, name, etc. Similarly, in JavaScript, properties can also be used to define characteristics of an object.
Create object
Since you want to learn objects, you must first have an object. Then the question arises, how to create an object in JavaScript? Next, let’s take a look at how to create objects in JavaScript.
Many books on JavaScript introduce methods of object creation, mainly including:
Use object literals to create objects (key-value)
Use new to create objects
Create objects using Object.create()
Use functions to create objects
Create objects using prototypes
Create objects using object literals
Object literal is the simplest form of creating objects. It aims to simplify the process of creating objects containing a large number of properties. The object literal is a mapping table composed of pairs of attribute names (keys) and attribute values (values). Key and value are separated by colons (:), and each pair of key/values is separated by commas (,). The entire mapping Tables are enclosed in curly braces ({}).
The syntax for creating objects through object literals is as follows:
var obj = { property_1: value_1, // property_# 可能是一个标识符... 2: value_2, // 或者是一个数字 // ..., "property n": value_n // 或是一个字符串 };
Here obj is the name of the created object, each property_i is an identifier (can be a name, number or string literal), and each value_i is its value, and this value is assigned to property_i. Let’s look at a specific example:
var girl = { 'name': '欣欣', 'age' : 18, 'height': 175, 'weight': 45 }
This example creates an object named girl. The object has four attributes: name, age, height and weight. These four attributes correspond to an attribute value.
When creating an object using object literals, if you leave its curly braces ({}) empty, you can define an object containing only default properties and methods. Such as:
var obj = {}
When using an object created in this way, you can create object attributes for object obj through the dot (.), that is, obj.key, and assign the object's attribute value. In addition, you can also create object attributes for the object obj through square brackets ([]), that is, obj['key'], and assign the object's attribute values. As an example below:
var girl = {}; girl.name = '欣欣'; girl.age = 18; girl['height'] = 175; girl['weight'] = 45;
When printing the girl object in Chrome, the output result is as follows:
console.log(girl); //Object {name: "欣欣", age: 18, height: 175, weight: 45}
Use new to create objects
You can also create objects by using the new operator followed by the Object constructor (more on the constructor later):
var obj = new Object(); // Same as obj = {}
Although obj is an empty object in the initial state, members can be easily added and used dynamically in JavaScript, so we can continue to add member variables and methods. Such as:
var girl = new Object(); girl['name'] = '欣欣'; girl['age'] = 18; girl['height'] = 175; girl['weight'] = 45;
Use Object.create() to create objects
Objects can also be created using the Object.create() method. This method is useful because it allows you to choose the prototype object for the created object without defining a constructor.
The Object.create() method creates an object with the specified prototype and several specified properties.
Object.create(proto, [ propertiesObject ])
The Object.create() method creates an object and accepts two parameters. The first parameter is the prototype object proto of this object; the second is an optional parameter to further describe the properties of the object. . This method is very simple to use:
var obj1 = Object.create({ x: 1, y: 2 }); //对象obj1继承了属性x和y var obj2 = Object.create(null); //对象obj2没有原型
如果 proto 参数不是 null 或一个对象值,则抛出一个 TypeError 异常。
有关于Object.create()方法更多的示例可以点击这里进行了解。
使用函数创建对象
在实际使用当中,字面量创建对象虽然很有用,但是它并不能满足我们的所有需求,我们希望能够和其他后台语言一样创建一个类,然后声明类的实例就能够多次使用,而不用每次使用的时候都要重新创建它。
因为JavaScript没有类,一般都是使用函数来定义一个类似其他语言中的类格式,比如:
function Person() { this.name = "mary"; // 为这个类添加一个成员变量name,并为这个成员变量赋默认值 this.age = 5; this.sayHello = function () { console.log(this.name + " : " + this.age); }; }
定义好类之后,我们就可以像下面这样创建和使用对象:
var person1 = new Person(); person1.name = 'Tom'; person1.age = 20; person1.sayHello(); // Tom : 20 var person2 = new Person(); person2.name = 'W3cplus'; person2.age = 5; person2.sayHello(); // W3cplus : 5
Person()函数不是用来被调用的,它是用来被new用的。
通过原型创建对象
这种方法比较前几种方法来说算是最为复杂,最为高级的方法。这里还涉及到封装的一些知识(有关于这些后续学习到了再记录)。这里简单看看如何通过原型创建对象。
首先像函数方法创建对象一样,先定义一个函数:
function Person() { this.name = "W3cplus"; this.age = 5; this.walk = function () { console.log("一个前端网站..."); }; }
然后在外部可以扩允成员:
//添加成员方法 Person.prototype.sayHello = function () { console.log("hello"); }; //也可以添加成员属性, Person.prototype.height = 100;
一方面,原型可以扩充原有类的功能(特别是添加有用方法),也可以像下面这样写:
function Person() { } Person.prototype.name = "W3cplus"; Person.prototype.age = 5; Person.prototype.walk = function () { console.log("一个前端网站..."); }; Person.prototype.sayHello = function () { console.log("hello"); }; Person.prototype.height = 100;
属性访问
对象属性访问一般有两种方法,第一种是使用点(.)表示法,这也是最常用的一种方法,也是很多面向对象语言中通用的语法。第二种方法还可以使用中括号([])表示法来访问对象的属性。在使用中括号语法时,应该将要访问的属性以字符串的形式放在中括号中。如下:
person['name']; person.name;
从功能上来说,上面两种方法访问对象属性没有任何区别。但中括号语法的主要优点有两个:
可能通过变量访问属性,如下:
var propertyName = 'name'; person[propertyName];
另外一个优点是,如果属性名中包含了会导致语法错误的字符或者属性名使用的是关键字或保留字,可以使用中括号访问属性,如下:
person['first name'];
一般情况之下,除非必须使用亦是来访问对象属性,否则建议使用点(.)的方法来访问对象属性。
总结
对象是JavaScript的基本数据类型,如果要更好的往下学习JavaScript相关的知识,很有必要先把对象整明白。这篇主要介绍了几种创建对象的方法。较为简单的是通过字面量({})和new Object()方法创建,但这两种方法创建的对象复用性较差;使用Object.create()创建对象时不需要定义一个构造函数就允许你在对象中选择其原型对象。除了这几种方法还可以使用函数和原型创建对象,而这两种方法相对来说可复用性强,只是使用较为复杂。
有关JavaScript学习笔记之创建对象的知识小编就给大家介绍到这里,希望对大家有所帮助!