search
HomeWeb Front-endJS TutorialJavaScript object-oriented programming basics_basic knowledge

Re-understand object-oriented
In order to illustrate that JavaScript is a completely object-oriented language, it is first necessary to start with the concept of object-oriented and discuss several concepts in object-oriented:

  1. Everything is an object
  2. Objects have encapsulation and inheritance features
  3. Objects use messages to communicate with each other, and each has information hiding

Based on these three points, C is a semi-object-oriented and semi-procedural language, because although it implements class encapsulation, inheritance and polymorphism, there are non-object global functions and variables. Java and C# are completely object-oriented languages. They organize functions and variables in the form of classes so that they cannot exist without objects. But here the function itself is a process, just attached to a certain class.

However, object-oriented is just a concept or programming idea, and it should not depend on a certain language for its existence. For example, Java uses object-oriented thinking to construct its language, and it implements mechanisms such as classes, inheritance, derivation, polymorphism, and interfaces. However, these mechanisms are only a means to implement object-oriented programming, not necessary. In other words, a language can choose an appropriate way to implement object orientation based on its own characteristics. Therefore, since most programmers first learn or use high-level compiled languages ​​such as Java and C (although Java is semi-compiled and semi-interpreted, it is generally explained as a compiled language), they preconceivedly accept the term "class". Object-oriented implementation method, so when learning scripting languages, it is customary to use the concepts in class-based object-oriented languages ​​to judge whether the language is an object-oriented language or whether it has object-oriented characteristics. This is also one of the important reasons that hinders programmers from learning and mastering JavaScript in depth.
In fact, the JavaScript language implements object-oriented programming through a method called prototype. Let's discuss the differences between the two methods of constructing the objective world, class-based object-oriented and prototype-based object-oriented.
Comparison between class-based object-oriented and prototype-based object-oriented approaches
In the class-based object-oriented approach, objects are generated based on classes. In the prototype-based object-oriented approach, objects are constructed using constructors and prototypes. Give an example from the objective world to illustrate the difference between the two ways of cognition. For example, when a factory builds a car, on the one hand, workers must refer to an engineering drawing and the design stipulates how the car should be manufactured. The engineering drawings here are like classes in language, and cars are manufactured according to this class; on the other hand, workers and machines (equivalent to constructors) use various parts such as engines, tires, The steering wheel (equivalent to each attribute of the prototype) constructs the car.
In fact, there is still debate about which of the two methods expresses object-oriented ideas more thoroughly. But the author believes that prototype object-oriented is a more thorough object-oriented approach for the following reasons:
First of all, the creation of objects in the objective world is the result of the construction of other physical objects, and abstract "drawings" cannot produce "cars". In other words, a class is an abstract concept rather than an entity, and the creation of objects is The creation of an entity;
Secondly, according to the most basic object-oriented rule that everything is an object, the class itself is not an object. However, the constructor and prototype in the prototype method are themselves other objects through the prototype method. Constructed object.
Thirdly, in a class-based object-oriented language, the state of an object is held by the object instance, and the behavior method of the object is held by the class that declares the object, and only the structure and Methods can be inherited; in prototype object-oriented languages, the behavior and status of the object belong to the object itself and can be inherited together (reference resources), which is closer to objective reality.
Finally, class-based object-oriented languages ​​such as Java allow static properties and static methods to be declared in classes in order to make up for the inconvenience of not being able to use global functions and variables in procedural languages. In fact, there is no so-called static concept in the objective world, because everything is an object! In a prototype object-oriented language, except for built-in objects, global objects, methods or properties are not allowed to exist, and there is no static concept. All language elements (primitives) must depend on objects for their existence. However, due to the characteristics of functional languages, the objects on which language elements depend change with changes in the runtime context, which is specifically reflected in changes in the this pointer. It is this characteristic that is closer to the natural view that "everything belongs to something, and the universe is the foundation for the survival of all things."


JavaScript object-oriented basic knowledge

Although JavaScript itself does not have the concept of classes, it still has object-oriented characteristics, although it is different from common object-oriented languages.

The simple way to create an object is as follows:

function myObject() {

};

JavaScript 中创建对象的方法一般来说有两种:函数构造法和字面量法,上面这种属函数构造法。下面是一个字面量法的例子:

var myObject = {

};

If you only need one object and do not need other instances of the object, it is recommended to use the literal method. If multiple instances of an object are required, the function constructor is recommended.
Define properties and methods

Function construction method:

function myObject() {
 this.iAm = 'an object';

 this.whatAmI = function() {
 console.log('I am ' + this.iAm);
 };
};

Literal method:

var myObject = {
 iAm : 'an object',

 whatAmI : function() {
 console.log('I am ' + this.iAm);
 }
};

The objects created by the above two methods have a property named "iAm" and a method named "whatAmI". Properties are variables in an object, and methods are functions in an object.

How to get attributes and call methods:

var w = myObject.iAm;

myObject.whatAmI();

When calling a method, you must add parentheses after it. If you do not add parentheses, then it will just return a reference to the method.
The difference between the two methods of creating objects

  • When defining properties and methods in the function constructor, you must use the prefix this, which is not required in the literal method.
  • The function constructor uses = when assigning values ​​to properties and methods, and the literal method uses : .
  • If there are multiple properties or methods, they should be separated by ; in the function constructor and by , in the literal method.

For objects created by literal method, you can directly call its properties or methods using the reference of the object:

myObject.whatAmI();

For the function constructor, you need to create an instance of the object before you can call its properties or methods:

var myNewObject = new myObject();
myNewObject.whatAmI();

Use constructor

Now let’s return to the previous function construction method:

function myObject() {
 this.iAm = 'an object';
 this.whatAmI = function() {
 console.log('I am ' + this.iAm);
 };
};

Actually, it looks like a function. Since it is a function, can I pass parameters to it? Modify the code slightly:

function myObject(what) {
 this.iAm = what;
 this.whatAmI = function(language) {
 console.log('I am ' + this.iAm + ' of the ' + language + ' language');
 };
};

Then instantiate the object and pass in the parameters:

var myNewObject = new myObject('an object');
myNewObject.whatAmI('JavaScript');

The final output of the program is I am an object of the JavaScript language.
There are two ways to create objects, which one should I use?

For literal methods, because it does not require instantiation, if the value of an object is modified, the value of the object is permanently modified, and any other access will be the modified value. . For the function constructor, when modifying the value, the value of its instance is modified. It can instantiate N objects, and each object can have its own different value without interfering with each other. Compare the following code snippets.

Let’s look at the literal method first:

var myObjectLiteral = {
 myProperty : 'this is a property'
};

console.log(myObjectLiteral.myProperty); // log 'this is a property'

myObjectLiteral.myProperty = 'this is a new property';

console.log(myObjectLiteral.myProperty); // log 'this is a new property'

Even if a new variable is created to point to this object, the result is still the same:

var myObjectLiteral = {
 myProperty : 'this is a property'
};

console.log(myObjectLiteral.myProperty); // log 'this is a property'

var sameObject = myObjectLiteral;

myObjectLiteral.myProperty = 'this is a new property';

console.log(sameObject.myProperty); // log 'this is a new property'

Look at the function construction method again:

// 用函数构造法
var myObjectConstructor = function() {
   this.myProperty = 'this is a property'
};

// 实例化一个对象
var constructorOne = new myObjectConstructor();

// 实例化第二个对象
var constructorTwo = new myObjectConstructor();

// 输出
console.log(constructorOne.myProperty); // log 'this is a property'

// 输出
console.log(constructorTwo.myProperty); // log 'this is a property'

和预期一样,两个对象的属性值是一样的。如果修个其中一个对象的值呢?

// 用函数构造法
var myObjectConstructor = function() {
 this.myProperty = 'this is a property';
};

// 实例化一个对象
var constructorOne = new myObjectConstructor();

// 修改对象的属性
constructorOne.myProperty = 'this is a new property';

// 实例化第二个对象
var constructorTwo = new myObjectConstructor();

// 输出
alert(constructorOne.myProperty); // log 'this is a new property'

// 输出
alert(constructorTwo.myProperty); // log 'this is a property'

As you can see, different objects instantiated using the function constructor are independent of each other and can each have different values. Therefore, which method to use to create objects depends on the actual situation.

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use