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
    
  • 相关阅读:
    SD卡性能测试
    在程序内动态获取svn版本号
    在SharePoint 2010程序中使用Session
    图片预读
    CSS图片垂直居中方法整理集合 !(常见问题解答)
    cpld的入门交流之二:秒信号发生器
    基于json数据的jQuery无限级下拉菜单插件
    MySQL 按指定字段自定义列表排序
    10张图让你更了解博客
    IE6 CSS bug: position:relative变成了absolute
  • 原文地址:https://www.cnblogs.com/CyLee/p/9862384.html
Copyright © 2011-2022 走看看