栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript中的静态变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript中的静态变量

如果您来自基于类的静态类型的面向对象的语言(例如Java,C++或C#),那么我假设您正在尝试创建与“类型”相关但与实例无关的变量或方法。

使用带有构造函数的“经典”方法的示例可能会帮助您了解基本的OO Javascript概念:

function MyClass () { // constructor function  var privateVariable = "foo";  // Private variable  this.publicVariable = "bar";  // Public variable  this.privilegedMethod = function () {  // Public Method    alert(privateVariable);  };}// Instance method will be available to all instances but only load once in memory MyClass.prototype.publicMethod = function () {      alert(this.publicVariable);};// Static variable shared by all instancesMyClass.staticProperty = "baz";var myInstance = new MyClass();

staticProperty
是在MyClass对象(它是一个函数)中定义的,并且与创建的实例无关,Javascript将函数视为一等对象,因此作为对象,可以为函数分配属性。

更新: ES6引入了通过关键字声明类的功能

class
。它是对现有基于原型的继承的语法糖。

static
关键字允许您轻松地在一个类中定义的静态属性或方法。

让我们看一下上面用ES6类实现的示例:

class MyClass {  // class constructor, equivalent to  // the function body of a constructor  constructor() {    const privateVariable = 'private value'; // Private variable at the constructor scope    this.publicVariable = 'public value'; // Public property    this.privilegedMethod = function() {      // Public Method with access to the constructor scope variables      console.log(privateVariable);    };  }  // Prototype methods:  publicMethod() {    console.log(this.publicVariable);  }  // Static properties shared by all instances  static staticProperty = 'static value';  static staticMethod() {    console.log(this.staticProperty);  }}// We can add properties to the class prototypeMyClass.prototype.additionalMethod = function() {  console.log(this.publicVariable);};var myInstance = new MyClass();myInstance.publicMethod();       // "public value"myInstance.additionalMethod(); // "public value"myInstance.privilegedMethod(); // "private value"MyClass.staticMethod();  // "static value"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号