Home Web Front-end Front-end Q&A What are public methods and private methods in javascript

What are public methods and private methods in javascript

Feb 07, 2022 pm 02:50 PM
javascript private method

In JavaScript, public methods refer to methods that can be accessed and called from the outside; while private methods refer to methods that are declared in the constructor of an object and are invisible and inaccessible to the outside.

What are public methods and private methods in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1: Public methods

Public methods are methods that can be accessed and called externally

// 对象中
var test1 = {
    name:'大白',
    getName:function(){
        console.log(this.name);
    }
}
//调用
test1.getName();//大白

// 构造函数中
function test2(name,age){
    this.name = name;
    this.age = age;
    //公有方法
    this.getName = function(){
        console.log(this.name);
    }
}
// 在原型中
test2.prototype.getAge = function(){
    console.log(this.age);
}
//调用
var test3 = new test2('小白',12);
test3.getName();//小白
test3.getAge();//12
Copy after login

2: Private methods and public methods

Privileged methods refer to public methods that have access to internal private properties and private methods ( Able to access private methods and private attribute methods are called privileged methods, which are also a type of public methods)

Private methods are declared in the constructor of the object and are not visible and accessible from the outside. Methods.

Use different ways to define private methods and privileged methods in different forms

In objectsWe use Object object expressions to create an object and add some properties and methods, Then call it directly in a static way. Such as Rest.getName();

Immediate execution functionThe private data of the object is placed in an anonymous function immediate execution expression (IIFE), which means that this function only exists when it is called The moment it is executed, it will be destroyed immediately

var yourObject = (function() {

 // 私有属性和方法
 return {
 // 公有方法和属性
 }
}) ();
Copy after login

This is the same as the previous definition of Rest, and can be accessed directly through yourObject. This kind of modular access is quite powerful.

var test4 = (function(){
    //私有属性
    var total = 10;
    // 私有方法
    var buy = function(){
        total--;
    }
    var get = function(){
        return total;
    }
    return {
        name:'小白白',
        getTotal:get,//使用了闭包的方式来简介使用内部私有变量
        buyfood:buy
    }
})();
test4.buyfood();
console.log(test4.name);//小白白
console.log(test4.getTotal());//9
Copy after login

Uses closure to indirectly use internal private variables

It is convenient to define private properties and methods in the constructor, we don’t If you need to use a closure, you can initialize the data when calling

// 构造函数中

function test5(name) {
 // 私有属性
 var total = 10;

 // 公有属性
 this.name = name;

 // 私有方法
 function _buyFood() {
    total--;
 }

 // 特权方法,才能访问私有的属性和私有的方法
 this.buy = function() {
     _buyFood();
 }

 this.getTotal = function() {
    return total;
 }
}

// 公有方法, 注意这里不能访问私有成员_total
test5.prototype.getName = function() {
    //console.log(_total); // Uncaught ReferenceError: _total is not defined
    return this.name;
}

var test6 = new test5('大小白');
console.log(test6.getName()); // '大小白'
test6.buy();
console.log(test6.getTotal()); // 9
Copy after login

Used in conjunction with

Using the constructor method, you can pass in some initialized data , but private member attributes cannot be accessed in public methods. If there are many public methods that need to access private data, we will write them all in privileged methods, which will eventually bring many unnecessary methods to each instance.

var test7 = (function(){
    // 私有属性
    var total = 10;

    // 私有方法
    function buyFood(){
        total--;
    }
    // 构造函数
    function test7(name){
        this.name = name;
        this.getTotal = function(){
            return total;
        }
    }
    // 公有方法  这里不是test7内部的私有
    test7.prototype.buy = function(){
        console.log(total);
        buyFood();
    }
    test7.prototype.getName = function(){
        return this.name;
    }
    return test7;
})();
var test0 = new test7('大大白');
console.log(test0.getName());//大大白
test0.buy();//10
console.log(test0.getTotal());//9
Copy after login

【Related recommendations: javascript learning tutorial

The above is the detailed content of What are public methods and private methods in javascript. For more information, please follow other related articles on 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 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 an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles