Javascript static variable in function

static

Ключевое слово static определяет статический метод или свойство для класса или блок статической инициализации класса (см. ссылку для получения дополнительной информации об этом использовании). Ни статические методы, ни статические свойства не могут быть вызваны для экземпляров класса. Вместо этого они вызываются в самом классе.

Статические методы часто представляют собой полезные функции,например,функции для создания или клонирования объектов,тогда как статические свойства полезны для кэшей,фиксированной конфигурации или любых других данных,которые не нужно реплицировать между экземплярами.

Примечание. В контексте классов в содержимом веб-документов MDN термины свойства и поля взаимозаменяемы.

Try it

Syntax

static methodName() < /* … */ > static propertyName [= value]; // Блок статической инициализации класса static

Examples

Использование статических членов в классах

Следующий пример демонстрирует несколько вещей:

  1. Как статический член (метод или свойство)определяется в классе.
  2. Что класс со статическим членом может быть подклассом.
  3. Как можно и как нельзя вызывать статический член.
class Triple < static customName = 'Tripler'; static description = 'I triple any number you provide'; static calculate(n = 1) < return n * 3; > > class SquaredTriple extends Triple < static longDescription; static description = 'I square the triple of any number you provide'; static calculate(n) < return super.calculate(n) * super.calculate(n); > > console.log(Triple.description); // 'Я утрою любое указанное вами число' console.log(Triple.calculate()); // 3 console.log(Triple.calculate(6)); // 18 const tp = new Triple(); console.log(SquaredTriple.calculate(3)); // 81 (не зависит от родительского экземпляра) console.log(SquaredTriple.description); // 'Я возведу в квадрат тройное любое указанное вами число' console.log(SquaredTriple.longDescription); // undefined console.log(SquaredTriple.customName); // 'Tripler' // Это выбрасывается, потому что calculate () является статическим членом, а не членом экземпляра. console.log(tp.calculate()); // 'tp.calculate не является функцией' 

Вызов статических членов из другого статического метода

Чтобы вызвать статический метод или свойство в другом статическом методе того же класса, вы можете использовать ключевое слово this .

class StaticMethodCall < static staticProperty = 'static property'; static staticMethod( ) < return `Static method and $this.staticProperty> has been called`; > static anotherStaticMethod( ) < return `$this.staticMethod()> from another static method`; > > StaticMethodCall.staticMethod(); // 'Статический метод и статическое свойство были вызваны' StaticMethodCall.anotherStaticMethod(); // 'Статический метод и статическое свойство были вызваны из другого статического метода' 

Вызов статических членов из конструктора класса и других методов

Статические члены недоступны напрямую с помощью ключевого слова this из нестатических методов. Вам нужно вызывать их, используя имя класса: CLASSNAME.STATIC_METHOD_NAME() / CLASSNAME.STATIC_PROPERTY_NAME или вызывая метод как свойство constructor : this.constructor.STATIC_METHOD_NAME() / this.constructor.STATIC_PROPERTY_NAME

class StaticMethodCall < constructor( ) < console.log(StaticMethodCall.staticProperty); // 'статическое свойство' console.log(this.constructor.staticProperty); // 'статическое свойство' console.log(StaticMethodCall.staticMethod()); // 'статический метод был вызван.' console.log(this.constructor.staticMethod()); // 'статический метод был вызван.' > static staticProperty = 'static property'; static staticMethod( ) < return 'static method has been called.'; > >

Specifications

Источник

Читайте также:  Python call lambda function

Static Variables in JavaScript

Static Variables in JavaScript

  1. Use the Property of a Function to Create Static Variables in JavaScript
  2. Use IIFE (Immediately Invoked Function Expression) to Create Static Variables in JavaScript
  3. Use the arguments.callee to Create Static Variables in JavaScript
  4. Use Constructors to Create Static Variables in JavaScript

This tutorial introduces how to create static variables in JavaScript. Static variables are variables, typically used in functions, that maintain their value between function calls. The static keyword helps to define a static property or method of a class.

Use the Property of a Function to Create Static Variables in JavaScript

Functions in JavaScript are objects and can have properties. So, we can create static variables by declaring the function’s properties. They maintain their values like global variables and can’t be modified outside the functions, making them much tidier than global variables.

function getId()   if ( typeof getId.counter == 'undefined' )   getId.counter = 0;  >  alert(++getId.counter); > 

Calling the above function multiple times increases the counter’s value and can’t be accessed outside function like global variables stopping all the mess.

Use IIFE (Immediately Invoked Function Expression) to Create Static Variables in JavaScript

  1. An anonymous function with a lexical scope enclosed by the grouping operator () .
  2. Function expression that is directly interpreted by JavaScript.
var incr = (function ()   var i = 1;  return function ()   return i++;  > >)(); incr(); // returns 1  incr(); // returns 2 

Every time the function is called, the counter i increases by one. i is inaccessible outside because it is a function’s property, just like a typical static variable inside a class.

Use the arguments.callee to Create Static Variables in JavaScript

We can use arguments.callee to store static variables in JavaScript. It refers to the function being currently executed, and we can attach properties to it directly as we would to a function object.

function ()   arguments.callee.myStaticVar = arguments.callee.myStaticVar || 1;  arguments.callee.myStaticVar++;  alert(arguments.callee.myStaticVar); > 

This method is pretty similar to method 1, the only difference being instead of directly attaching properties, we are using arguments.callee to add properties to the currently executing function.

Use Constructors to Create Static Variables in JavaScript

This method is the equivalent version of strongly-typed object-oriented languages like C++ / Java / C# . We try to assign variables to a whole type and not all instances.

function delftClass()   var privateVariable = "foo";  this.publicVariable = "bar";  this.privilegedMethod = function ()    alert(privateVariable);  >; > delftClass.prototype.publicMethod = function ()   alert(this.publicVariable); >;  delftClass.staticProperty = "baz"; var myInstance = new delftClass(); 

Here we create the construction function delftClass and then assign a static property that has nothing to do with the created instance. JavaScript treats functions as objects, so being an object, we can assign properties to a function. All the instances will share the static variable.

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

Related Article — JavaScript Variable

Источник

JavaScript static variable | Create and Use examples

First, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. But JavaScript doesn’t support static variables or a direct way to create them.

There is no static keywords in JavaScript. But you can implement function static variables in JavaScript and use them for purposes.

JavaScript static variable Example

A function is also an object in JavaScript and an object can have its own methods and properties. You can store function variables as object’s properties.

      

Create JavaScript static variable

Static variable count in Function

You can change the value or increase static variables in the function body. This is useful when the static variable is used for counting.

Let’s see complete HTML example code for it:-

      

JavaScript Static variable count in Function

Do comment if you any doubts and suggestion on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Источник

[Solved-5 Solutions] Static Variable in JavaScript — JavaScript tutorial

staticProperty is defined in the WikitechyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as first-class objects , so being an object, we can assign properties to a function.

Solution 2:

  • One of the main advandage of JavaScript functions are also objects, which means they can have properties.
  • For example the sample code is given below:
 function countMyself() < // Check to see if the counter has been initialized if ( typeof countMyself.counter == 'undefined' ) < // It has not. perform the initialization countMyself.counter = 0; >// Do something stupid to indicate the value alert(++countMyself.counter); > 
  • If we call that function several time, you’ll see the counter is being incremented.
  • Maybe the better solution using the global namespace with a global variable.
  • Here we can use simple code for static variables in javascript:
 var uniqueID = (function() < var // This is the private persistent value // The outer function returns a nested function that has access // to the persistent value. It is this nested function we're storing // in the variable uniqueID above. return function() < return id++; >; // Return and increment >)(); // Invoke the outer function after defining it. 

We will be getting same output except, this time, the incremented value is returned, instead of displayed.

Read Also

Solution 3:

We can do it through an IIFE (Immediately Invoked Function Expression):

 var incre = (function () < var j = 1; return function () < return j++; >>)(); incre(); // returns 1 incre(); // returns 2 

Solution 4:

We can use arguments.callee to store «static» variables (this is useful in anonymous function too):

Read Also

Solution 5:

If we want to declare static variables for creating constants in our application then we found following as most simplistic approach

 FruitConstants = (function() < var obj = <>; obj.APPLE = 'apple'; obj.ORANGE = 'orange'; obj.MANGO = 'mango'; obj.ALL = [obj.APPLE, obj.ORANGE, obj.MANGO]; return obj; >)(); //Example usage. var appleFruit = FruitConstants.APPLE; 

UP NEXT IN Javascript

static variable in javascript w3schools javascript static property es6 es6 static variable static variable in jquery javascript static es6 javascript static variable w3school how to assign value to static variable in javascript javascript class static method static variable in javascript example static variable in javascript w3schools static variable in javascript es6 static variable in jquery javascript static variable w3school javascript static property es6 javascript static es6 es7 static properties javascript tutorial java script javascript javascript array javascript book learn javascript javascript code javascript editor javascript class javascrip javascript debugger javascript online javascript examples javascript test javascript document javascript slider what is javascript javascript form validation javascript validator html javascript javascript alert javascript events javascript print javascript dom javascript object javascript function href javascript javascript date javascript prompt javascript onclick javascript return javascript for javascript number javascript confirm javascript onchange javascript regular expression javascript if javascript variable javascript timer javascript cookie javascript getelementbyid javascript innerhtml javascript call javascript regexp javascript includes javascript this javascript eval

    INTERVIEW TIPS
  • Final Year Projects
  • HR Interview Q&A
  • GD Interview
  • Resume Samples
  • Engineering
  • Aptitude
  • Reasoning
  • Company Questions
  • Country wise visa
  • Interview Dress Code CAREER GUIDANCE
  • Entrance Exam
  • Colleges
  • Admission Alerts
  • ScholarShip
  • Education Loans
  • Letters
  • Learn Languages

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

Оцените статью