search
HomeWeb Front-endJS TutorialLearn Javascript object-oriented programming encapsulation_javascript skills

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.
So, if we want to encapsulate "property" and "method" into an object, or even generate an instance object from the prototype object, what should we do?
1. Original mode of generating objects
Suppose we regard the cat as an object, which has two attributes: "name" and "color".

var Cat = {
    name : '',
    color : ''
  }

Now, we need to generate two instance objects based on the specification (schema) of this prototype object.

var cat1 = {}; // 创建一个空对象
    cat1.name = "大毛"; // 按照原型对象的属性赋值
    cat1.color = "黄色";
  var cat2 = {};
    cat2.name = "二毛";
    cat2.color = "黑色";

Okay, this is the simplest encapsulation, encapsulating two properties into an object. However, this way of writing has two disadvantages. First, if more instances are generated, it will be very troublesome to write; second, there is no way to see the connection between the instances and the prototype.
2. Improvements to the original mode
We can write a function to solve the problem of code duplication.

function Cat(name,color){
    return {
      name:name,
      color:color
    }
  }

Then generating an instance object is equivalent to calling a function:

var cat1 = Cat("大毛","黄色");
  var cat2 = Cat("二毛","黑色");

The problem with this method is still that there is no intrinsic connection between cat1 and cat2, and it cannot reflect that they are instances of the same prototype object.
3. Constructor pattern
In order to solve the problem of generating instances from prototype objects, Javascript provides a constructor (Constructor) pattern.
The so-called "constructor" is actually an ordinary function, but the this variable is used internally. Using the new operator on the constructor will generate an instance, and the this variable will be bound to the instance object.
For example, the prototype object of cat can now be written like this,

 function Cat(name,color){
    this.name=name;
    this.color=color;
  }

We can now generate instance objects.

 var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat("二毛","黑色");
  alert(cat1.name); // 大毛
  alert(cat1.color); // 黄色

At this time, cat1 and cat2 will automatically contain a constructor attribute pointing to their constructor.

alert(cat1.constructor == Cat); //true
  alert(cat2.constructor == Cat); //true

Javascript also provides an instanceof operator to verify the relationship between prototype objects and instance objects.

 alert(cat1 instanceof Cat); //true
  alert(cat2 instanceof Cat); //true

4. Problems with constructor pattern
The constructor method is easy to use, but there is a problem of wasting memory.
Please see, we now add an immutable attribute "type" (type) to the Cat object, and then add a method eat (eat mice). Then, the prototype object Cat becomes as follows:

 function Cat(name,color){
    this.name = name;
    this.color = color;
    this.type = "猫科动物";
    this.eat = function(){alert("吃老鼠");};
  }

Use the same method to generate an instance:

 var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat ("二毛","黑色");
  alert(cat1.type); // 猫科动物
  cat1.eat(); // 吃老鼠

On the surface, there seems to be no problem, but in fact, there is a big disadvantage in doing this. That is, for each instance object, the type attribute and eat() method have exactly the same content. Every time an instance is generated, it must occupy more memory for repeated content. This is neither environmentally friendly nor efficient. ​

alert(cat1.eat == cat2.eat); //false

Can the type attribute and eat() method be generated only once in memory, and then all instances point to that memory address? The answer is yes.
5. Prototype mode
Javascript stipulates that each constructor has a prototype attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.
This means that we can define those immutable properties and methods directly on the prototype object:

 function Cat(name,color){
    this.name = name;
    this.color = color;
  }
  Cat.prototype.type = "猫科动物";
  Cat.prototype.eat = function(){alert("吃老鼠")};

Then, generate the instance.

 var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat("二毛","黑色");
  alert(cat1.type); // 猫科动物
  cat1.eat(); // 吃老鼠

At this time, the type attribute and eat() method of all instances are actually the same memory address, pointing to the prototype object, thus improving operating efficiency.

 alert(cat1.eat == cat2.eat); //true

6. Verification method of Prototype mode
In order to cooperate with the prototype attribute, Javascript defines some auxiliary methods to help us use it. ,
6.1 isPrototypeOf()
This method is used to determine the relationship between a certain proptotype object and an instance.

 alert(Cat.prototype.isPrototypeOf(cat1)); //true
  alert(Cat.prototype.isPrototypeOf(cat2)); //true

6.2 hasOwnProperty()
Each instance object has a hasOwnProperty() method, which is used to determine whether a certain property is a local property or a property inherited from the prototype object.

 alert(cat1.hasOwnProperty("name")); // true
  alert(cat1.hasOwnProperty("type")); // false

6.3 in operator
The in operator can be used to determine whether an instance contains a certain attribute, whether it is a local attribute or not.

 alert("name" in cat1); // true
  alert("type" in cat1); // true
The

in operator can also be used to traverse all properties of an object.

 for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }

The above is all about javascript encapsulation. I hope it will be helpful to everyone's learning.

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

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool