Home >Web Front-end >JS Tutorial >Is javascript based on objects?
Javascript is object-oriented. Each built-in object of js is derived from object, so there are three object-oriented features of inheritance, polymorphism and reconstruction, even if js is now based on prototype Pseudo-inheritance, but the general idea is an object-oriented language.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Compared with other languages, "objects" in JavaScript always seem not so gregarious. When some newcomers learn JavaScript object-oriented, they often have doubts: Why does JavaScript (until ES6) have the concept of objects, but not the concept of classes like other languages? Why can we freely add properties to JavaScript objects, but not other languages?
Even in some debates, some people emphasized that JavaScript is not an "object-oriented language", but an "object-based language". This statement was once widely circulated, but in fact, the holders I have encountered so far No one who makes this statement can answer the question "How to define object-oriented and object-based".
In fact, the two adjectives object-based and object-oriented have appeared in various versions of the JavaScript standard. We can first look at the object-based definition of the JavaScript standard. The specific content of this definition is: "The infrastructure of the language and host is provided by objects, and the ECMAScript program is a collection of objects that communicate with each other." The meaning here is not to express the weakened object-oriented meaning at all, but to express the importance of objects to the language.
So, in this article, I will try to let you understand what object-oriented and object-oriented in JavaScript are.
Let’s first talk about what an object is. Due to translation reasons, it is difficult for us to understand the true meaning of “object” in the Chinese context. In fact, Object is the general term for everything in English, which has something in common with the abstract thinking of object-oriented programming. The Chinese "object" does not have such universality. In the process of learning programming, we understand it more as a professional term.
But no matter what, we should realize that objects are not a concept created out of thin air in the computer field. It is an abstraction that follows human thinking patterns (so object-oriented programming is also considered: closer A programming paradigm of the human mind).
So, let’s first take a look at what exactly an object is in the human thinking model.
The concept of objects was formed in human childhood, which is far earlier than the concepts such as values and procedures commonly used in our programming logic. In childhood, we always first realize that a certain apple can be eaten (a certain apple here is an object), then realize that all apples can be eaten (all apples here are a class), and then later we realize that Only then can we realize the connection between three apples and three pears, and then generate the concept of the number "3" (value).
In the book "Object-Oriented Analysis and Design", Grady Booch summarized it for us. He believes that from a human cognitive perspective, an object should be one of the following things:
A thing that can be touched or seen;
Something that can be understood by human intelligence;
Something that guides thinking or action (imagining or performing actions).
With the natural definition of objects, we can describe objects in programming languages. In different programming languages, designers also use various language features to abstractly describe objects. The most successful school is to use "classes" to describe objects, which gave birth to popular programming languages such as C and Java. In the early years, JavaScript chose a more unpopular method: prototypes (I will focus on prototypes in the next article, you can just leave an impression here). This is one of the reasons why I said earlier that it is unsociable.
Unfortunately, due to some company political reasons, JavaScript was ordered by management to imitate Java when it was launched. Therefore, JavaScript founder Brendan Eich introduced new, This and other language features make it "look more like Java".
Before the emergence of ES6, a large number of JavaScript programmers tried to make JavaScript more like class-based programming based on the prototype system, which resulted in many so-called "frameworks", such as PrototypeJS and Dojo. In fact, they became some kind of weird dialect of JavaScript, and even spawned a series of mutually incompatible communities. Obviously, the gains of doing so far outweighed the losses.
If we talk about objects from a runtime perspective, we are discussing the actual running model of JavaScript. This is because any code execution must inevitably avoid the runtime object model. However, fortunately, from From a runtime perspective, you don't have to be troubled by these "class-based facilities" because the concept of runtime classes in any language is weakened.
First of all, let’s take a look at how JavaScript designs the object model.
In my opinion, no matter what programming language we use, we should first understand the essential characteristics of the object (refer to Grandy Booch's "Object-Oriented Analysis and Design"). In summary, the object has the following characteristics.
Objects are uniquely identifiable: even two objects that are identical are not the same object.
Objects are stateful: Objects have states, and the same object may be in different states.
Objects have behaviors: that is, the state of the object may change due to its behavior.
Let’s look at the first feature first, the object is uniquely identifiable. Generally speaking, the unique identification of objects in various languages is reflected by memory addresses. Therefore, JavaScript programmers know that any different JavaScript objects are actually not equal to each other. We can look at the following code, o1 and o2 At first glance, they are two identical objects, but the printed result is false.
var o1 = { a: 1 }; var o2 = { a: 1 }; console.log(o1 == o2); // false
Regarding the second and third characteristics of objects, "state and behavior", different languages will use different terms to describe them abstractly. For example, C calls them "member variables" and "member functions" ", Java calls them "properties" and "methods".
In JavaScript, state and behavior are unified and abstracted as "properties". Considering that functions are designed as a special object in JavaScript (I will explain this in detail later, so there is no need to go into detail here. ), so behaviors and states in JavaScript can be abstracted using attributes.
The following code actually shows an example of ordinary attributes and functions as attributes, where o is an object, d is an attribute, and the function f is also an attribute. Although the writing method is not the same, it is suitable for JavaScript For example, d and f are two common attributes.
var o = { d: 1, f() { console.log(this.d); } };
So, to sum up, in JavaScript, the state and behavior of objects are actually abstracted into attributes. If you have used Java, don't be surprised. Although there are certain differences in design ideas, both of them well express the basic characteristics of objects: identity, status and behavior.
Based on realizing the basic characteristics of objects, I believe that the unique characteristics of objects in JavaScript are: objects are highly dynamic. This is because JavaScript allows users to add changes to objects at runtime. state and behavioral capabilities.
Let me give you an example. For example, JavaScript allows adding properties to objects at runtime, which is completely different from most class-based, static object designs. If you have used Java or other languages, you will definitely have the same feeling as me.
The following code shows how to add attributes to an object at runtime. At the beginning, I defined an object o. After the definition is completed, I added its attribute b. This operation is completely fine. . You have to understand this.
var o = { a: 1 }; o.b = 2; console.log(o.a, o.b); //1 2
In order to improve abstraction capabilities, JavaScript properties are designed to be more complex than other languages. It provides two types of data properties and accessor properties (getter/setter).
For JavaScript, attributes are not just simple names and values. JavaScript uses a set of characteristics to describe properties.
Let’s talk about the first type of attributes, data attributes. It is closer to the attribute concept of other languages. Data attributes have four characteristics.
value: It is the value of the attribute.
writable: Determines whether the attribute can be assigned a value.
enumerable: Determines whether for in can enumerate the property.
configurable: Determines whether the attribute can be deleted or the characteristic value can be changed.
In most cases, we only care about the value of the data attribute.
The second type of attribute is the accessor (getter/setter) attribute, which also has four characteristics.
getter: function or undefined, called when getting the property value.
setter: function or undefined, called when setting the property value.
enumerable: Determines whether for in can enumerate the property.
configurable: Determines whether the attribute can be deleted or the characteristic value can be changed.
The accessor attribute allows the property to execute code when reading and writing. It allows the user to get completely different values when writing and reading the property. It can be regarded as a function syntax. sugar.
The code we usually use to define attributes will generate data attributes, of which writable, enumerable, and configurable all default to true. We can use the built-in function Object.getOwnPropertyDescripter to view it, as shown in the following code:
var o = { a: 1 }; o.b = 2;//a和b皆为数据属性 Object.getOwnPropertyDescriptor(o,\u0026quot;a\u0026quot;) // {value: 1, writable: true, enumerable: true, configurable: true} Object.getOwnPropertyDescriptor(o,\u0026quot;b\u0026quot;) // {value: 2, writable: true, enumerable: true, configurable: true}
We use two syntaxes here to define the property. After defining the property, we use the JavaScript API to view the property. , we can find that the attributes defined in this way are all data attributes, and the default value of writeable, enumerable, and configurable is true.
If we want to change the characteristics of a property or define an accessor property, we can use Object.defineProperty. The example is as follows:
var o = { a: 1 }; Object.defineProperty(o, \u0026quot;b\u0026quot;, {value: 2, writable: false, enumerable: false, configurable: true});//a和b都是数据属性,但特征值变化了 Object.getOwnPropertyDescriptor(o,\u0026quot;a\u0026quot;); // {value: 1, writable: true, enumerable: true, configurable: true} Object.getOwnPropertyDescriptor(o,\u0026quot;b\u0026quot;); // {value: 2, writable: false, enumerable: false, configurable: true}o.b = 3;console.log(o.b); // 2
这里我们使用了Object.defineProperty来定义属性,这样定义属性可以改变属性的writable和enumerable,我们同样用Object.getOwnPropertyDescriptor来查看,发现确实改变了writable和enumerable特征。因为writable特征为false,所以我们重新对b赋值,b的值不会发生变化。
在创建对象时,也可以使用 get 和 set 关键字来创建访问器属性,代码如下所示:
var o = { get a() { return 1 } }; console.log(o.a); // 1
访问器属性跟数据属性不同,每次访问属性都会执行getter或者setter函数。这里我们的getter函数返回了1,所以o.a每次都得到1。
这样,我们就理解了,实际上JavaScript 对象的运行时是一个“属性的集合”,属性以字符串或者Symbol为key,以数据属性特征值或者访问器属性特征值为value。对象是一个属性的索引结构(索引结构是一类常见的数据结构,我们可以把它理解为一个能够以比较快的速度用key来查找value的字典)。我们以上面的对象o为例,你可以想象一下“a”是key。
这里{writable:true,value:1,configurable:true,enumerable:true}是value。我们在前面的类型课程中,已经介绍了Symbol类型,能够以Symbol为属性名,这是JavaScript对象的一个特色。
讲到了这里,如果你理解了对象的特征,也就不难理解我开篇提出来的问题。
你甚至可以理解为什么会有“JavaScript不是面向对象”这样的说法:JavaScript的对象设计跟目前主流基于类的面向对象差异非常大。而事实上,这样的对象系统设计虽然特别,但是JavaScript提供了完全运行时的对象系统,这使得它可以模仿多数面向对象编程范式(下一节课我们会给你介绍JavaScript中两种面向对象编程的范式:基于类和基于原型),所以它也是正统的面向对象语言。
JavaScript语言标准也已经明确说明,JavaScript是一门面向对象的语言,我想标准中能这样说正因为JavaScript的高度动态性的对象系统。
所以,我们应该在理解其设计思想的基础上充分挖掘它的能力,而不是机械地模仿其它语言。
要想理解JavaScript对象,必须清空我们脑子里“基于类的面向对象”相关的知识,回到人类对对象的朴素认知和面向对象的语言无关基础理论,我们就能够理解JavaScript面向对象设计的思路。
在这篇文章中,我从对象的基本理论出发,和你理清了关于对象的一些基本概念,分析了JavaScript对象的设计思路。接下来又从运行时的角度,介绍了JavaScript对象的具体设计:具有高度动态性的属性集合。
很多人在思考JavaScript对象时,会带着已有的“对象”观来看问题,最后的结果当然就是“剪不断理还乱”了。
【推荐学习:javascript高级教程】
The above is the detailed content of Is javascript based on objects?. For more information, please follow other related articles on the PHP Chinese website!