zoukankan      html  css  js  c++  java
  • es5 温故而知新 创建私有成员、私有变量、特权变量的方法

    其实js是不支持私有变量的。哪怕到es6的class语法。虽然有许多变相的方式。但非常冗余而不推崇。

    这里介绍的实际上也不是class语法,而是普通的函数,并且利用IIFE(闭包)的方式来实现私有。

    这种方式也被称为“模块模式”

    var person = (function(){
    	var age = 25
    
    	return {
    		name: 'Lee',
    
    		getAge: function () {
    			return age
    		},
    
    		setAge: function () {
    			age++
    		}
    	}
    }());
    
    console.log(person.name) // Lee
    console.log(person.getAge()) // 25
    
    person.age = 100 // hack try...
    console.log(person.getAge()) // 25

    构造函数的私有变量

    function Person(name) {
    	this.name = name
    	var age = 18
    
    	this.getAge = function () {
    		return age
    	}
    
    	this.setAge = function () {
    		age++
    	}
    }
    
    var person = new Person('Lee')
    console.log(person.name) // Lee
    console.log(person.getAge()) // 18
    
    person.age = 100 // hack try...
    Person.age = 100 // hack try...
    console.log(person.getAge()) // 18
    
  • 相关阅读:
    Liferay安装maven
    html之pre标签
    a标签使用注意事项
    AngularJS学习记录
    页面不能访问,抛出 spring java.lang.IllegalArgumentException: Name for argument type [java.lang.String] 异常
    ant编译的时候,报错文件不存在,以及版本不一致
    Eclipse 更改Java 版本的方法
    总结一下本次准备环境时遇到的问题,以供下次参考
    数据上下文中的AddOrUpdate方法
    推荐一款github管理神器SourceTree
  • 原文地址:https://www.cnblogs.com/CyLee/p/9862384.html
Copyright © 2011-2022 走看看