search
HomeWeb Front-endJS TutorialBrief analysis of classes and objects in JavaScript

Brief analysis of classes and objects in JavaScript

Sep 09, 2017 pm 01:48 PM
javascriptjsobject

1. Constructor method
This is a classic method and a method that must be taught in textbooks. It uses a constructor to simulate a "class", and uses the this keyword internally to refer to the instance object

 function Cat() {
    this.name = "大毛";
  }

When generating an instance, use the new keyword.

 var cat1 = new Cat();
  alert(cat1.name); // 大毛

The attributes and methods of the class can also be defined on the prototype object of the constructor.

  Cat.prototype.makeSound = function(){
    alert("喵喵喵");
  }

For a detailed introduction to this method, please read the series of articles I wrote "Javascript Object-Oriented Programming", so I won’t go into details here. Its main disadvantage is that it is relatively complicated, uses this and prototype, and is very laborious to write and read.
2. Object.create() method
In order to solve the shortcomings of the "constructor method" and generate objects more conveniently, the fifth edition of the international standard ECMAScript for Javascript (the third edition is currently popular), was proposed A new method Object.create().
Using this method, "class" is an object, not a function.

 var Cat = {
    name: "大毛",
    makeSound: function(){ alert("喵喵喵"); }
  };

Then, directly use Object.create() to generate an instance without using new.

var cat1 = Object.create(Cat);
  alert(cat1.name); // 大毛
  cat1.makeSound(); // 喵喵喵

Currently, the latest versions of all major browsers (including IE9) have deployed this method. If you encounter an old browser, you can use the following code to deploy it yourself.

 if (!Object.create) {
    Object.create = function (o) {
       function F() {}
      F.prototype = o;
      return new F();
    };
  }

This method is simpler than the "constructor method", but it cannot implement private properties and private methods, and cannot share data between instance objects. The simulation of "classes" is not comprehensive enough. .
3. Minimalist approach
Dutch programmer Gabor de Mooij proposed a new method that is better than Object.create(). He called this method the "minimalist approach". This is also the method I recommend.
3.1 Encapsulation
This method does not use this and prototype, and the code is very simple to deploy. This is probably why it is called the "minimalist method".
First of all, it also uses an object to simulate a "class". In this class, define a constructor createNew() to generate instances.

 var Cat = {
    createNew: function(){
      // some code here
    }
  };

Then, in createNew(), define an instance object and use this instance object as the return value.

 var Cat = {
    createNew: function(){
      var cat = {};
      cat.name = "大毛";
      cat.makeSound = function(){ alert("喵喵喵"); };
      return cat;
    }
  };

When used, call the createNew() method to get the instance object.

 var cat1 = Cat.createNew();
  cat1.makeSound(); // 喵喵喵

The advantage of this method is that it is easy to understand, has a clear and elegant structure, and conforms to the traditional "object-oriented programming" construct, so the following features can be easily deployed.
3.2 Inheritance
Let one class inherit another class, which is very convenient to implement. Just call the latter's createNew() method in the former's createNew() method.
First define an Animal class.

 var Animal = {
    createNew: function(){
      var animal = {};
      animal.sleep = function(){ alert("睡懒觉"); };
      return animal;
    }
  };

Then, in Cat’s createNew() method, call Animal’s createNew() method.

  var Cat = {
    createNew: function(){
      var cat = Animal.createNew();
      cat.name = "大毛";
      cat.makeSound = function(){ alert("喵喵喵"); };
      return cat;
    }
  };

The Cat instance obtained in this way will inherit both the Cat class and the Animal class.

var cat1 = Cat.createNew();
  cat1.sleep(); // 睡懒觉

3.3 Private properties and private methods
In the createNew() method, as long as the methods and properties are not defined on the cat object, they are private.

  var Cat = {
    createNew: function(){
      var cat = {};
      var sound = "喵喵喵";
      cat.makeSound = function(){ alert(sound); };
      return cat;
    }
  };

The internal variable sound in the above example cannot be read externally and can only be read through the public method makeSound() of cat.

 var cat1 = Cat.createNew();
  alert(cat1.sound); // undefined

3.4 Data Sharing
Sometimes, we need all instance objects to be able to read and write the same internal data. At this time, just encapsulate the internal data inside the class object and outside the createNew() method.

  var Cat = {
    sound : "喵喵喵",
    createNew: function(){
      var cat = {};
      cat.makeSound = function(){ alert(Cat.sound); };
      cat.changeSound = function(x){ Cat.sound = x; };
      return cat;
    }
  };

Then, two instance objects are generated:

  var cat1 = Cat.createNew();
  var cat2 = Cat.createNew();
  cat1.makeSound(); // 喵喵喵

At this time, if there is an instance object, modify Without shared data, another instance object will also be affected.

  cat2.changeSound("啦啦啦");
  cat1.makeSound(); // 啦啦啦

The above is the detailed content of Brief analysis of classes and objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.