Home Web Front-end JS Tutorial Javascript Object-Oriented Programming (1) Encapsulation

Javascript Object-Oriented Programming (1) Encapsulation

Jan 04, 2017 am 09:26 AM
object-oriented

Javascript Object-oriented Programming (1): Encapsulation

Author: Ruan Yifeng

Javascript is an object-based language. 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. The original mode of generating objects

Suppose we regard the cat as an object, which has two attributes: "name" and "color".

var Cat = { 
    name : '', 
    color : '' 
  }
Copy after login

Now, we need to generate two instance objects based on this prototype object.

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

Okay, this is the simplest encapsulation. 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. Improvement of the original model
We can write a function to solve the problem of code duplication.

  function Cat(name,color){ 
    return { 
      name:name, 
      color:color 
    } 
  }
Copy after login

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

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

The problem with this method is still that there is no intrinsic connection between cat1 and cat2, and it cannot reflect that they are the same An instance of a 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; 
  }
Copy after login

We can now generate instance objects.

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

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
Copy after login

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

  alert(cat1 instanceof Cat); //true 
  alert(cat2 instanceof Cat); //true
Copy after login

4. Problems with the constructor pattern
The constructor method is easy to use, but there is a problem of wasting memory.
Please see, we now add an unchanged 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("吃老鼠");}; 
  }
Copy after login

Still use the same method to generate an instance:

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

On the surface, there seems to be no problem, but in fact, there is a very big problem when doing this Big disadvantage. 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 unchanged 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("吃老鼠")};
Copy after login

Then, generate an instance.

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

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. Prototype mode verification method
6.1 isPrototypeOf()
This method is used to determine whether a certain proptotype object and a certain relationship between instances.

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

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
Copy after login

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
Copy after login

The in operator can also be used to traverse all properties of an object.
 for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }


More Javascript for Object Programming (1) For encapsulation-related articles, please pay attention to the PHP Chinese website!


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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement object-oriented event-driven programming using Go language How to implement object-oriented event-driven programming using Go language Jul 20, 2023 pm 10:36 PM

How to use Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

What is the importance of @JsonIdentityInfo annotation using Jackson in Java? What is the importance of @JsonIdentityInfo annotation using Jackson in Java? Sep 23, 2023 am 09:37 AM

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Aug 14, 2023 pm 05:25 PM

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

C# development experience sharing: object-oriented programming and design principles C# development experience sharing: object-oriented programming and design principles Nov 22, 2023 am 08:18 AM

C# (CSharp) is a powerful and popular object-oriented programming language that is widely used in the field of software development. During the C# development process, it is very important to understand the basic concepts and design principles of object-oriented programming (OOP). Object-oriented programming is a programming paradigm that abstracts things in the real world into objects and implements system functions through interactions between objects. In C#, classes are the basic building blocks of object-oriented programming and are used to define the properties and behavior of objects. When developing C#, there are several important design principles

See all articles