zoukankan      html  css  js  c++  java
  • 私有变量

    构造函数的私有变量,属性和方法都是独立的。

     1 window.onload = function() {
     2     var person = new Person("Li");
     3     alert(person.getName());        // Li
     4     person.setName("Joe");
     5     alert(person.getName());        // Joe
     6 
     7     var person2 = new Person("Ji");
     8     alert(person2.getName());        // Ji
     9     person.setName("Joe");
    10     alert(person2.getName());        // Ji
    11 };
    12 
    13 /**
    14  * 人(每次调用构造函数都会重新创建方法)
    15  * @param {string} name 名字
    16  */
    17 function Person(name) {
    18     this.getName = function(){
    19         return name;
    20     };
    21 
    22     this.setName = function(value){
    23         name = value;
    24     }
    25 }

    静态私有变量,属性和方法都是共享的。

     1 window.onload = function() {
     2     var person = new Person("Li");
     3     alert(person.getName());        // Li
     4     person.setName("Joe");
     5     alert(person.getName());        // Joe
     6 
     7     var person2 = new Person("Ji");
     8     alert(person2.getName());        // Ji
     9     person.setName("Joe");
    10     alert(person2.getName());        // Joe
    11 };
    12 
    13 /**
    14  * 静态私有变量,属性和方法都是共享的,不会重复创建,但是实例之间会互相影响
    15  * @return {string} 姓名
    16  */
    17 (function(){
    18     var name = "";
    19 
    20     Person = function(value){
    21         name = value;
    22     };
    23 
    24     Person.prototype.getName = function(){
    25         return name;
    26     }
    27 
    28     Person.prototype.setName = function(value){
    29         name = value;
    30     };
    31 })();

     增强的模块模式,单例的特权方法。

     1 window.onload = function() {
     2     alert(application.getComponentCount());    // 1
     3     application.registerComponent("hello");
     4     alert(application.getComponentCount());    // 2
     5 };
     6 
     7 /**
     8  * 增强模块模式,单例的特权方法
     9  * @return {object}
    10  */
    11 var application = function(){
    12     // 私有变量和函数
    13     var components = new Array();
    14 
    15     // 初始化
    16     components.push(new String("hello"));
    17 
    18     // 创建apllication的一个局部副本
    19     var app = new String();
    20 
    21     // 公共接口
    22     app.getComponentCount = function(){
    23         return components.length;
    24     };
    25 
    26     app.registerComponent = function(str){
    27         if (typeof str == "string") {
    28             components.push(str);
    29         }
    30     };
    31 
    32     // 返回这个副本
    33     return app;
    34 }();
  • 相关阅读:
    Linux下Keepalived 安装与配置
    Nginx配置SSL证书部署HTTPS网站
    Nginx 实现MySQL的负载均衡
    iOS如何把导航默认的返回按钮设置成“返回”
    Java中JSON的简单使用与前端解析
    双机高可用、负载均衡、MySQL(读写分离、主从自动切换)架构设计
    iOS开发--使用RSA加密
    UIBezierPath画圆弧的记录
    SSL构建单双向https认证
    webpack配置上线地址
  • 原文地址:https://www.cnblogs.com/tinyTea/p/9946985.html
Copyright © 2011-2022 走看看