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
    
  • 相关阅读:
    hdu4998 旋转坐标系
    hdu4998 旋转坐标系
    hdu5012 水搜索
    hdu5012 水搜索
    hdu5007 小水题
    ZOJ 3645 BiliBili 高斯消元 难度:1
    ZOJ 3654 Letty's Math Class 模拟 难度:0
    ZOJ 3647 Gao the Grid dp,思路,格中取同一行的三点,经典 难度:3
    ZOJ 3646 Matrix Transformer 二分匹配,思路,经典 难度:2
    ZOJ 3644 Kitty's Game dfs,记忆化搜索,map映射 难度:2
  • 原文地址:https://www.cnblogs.com/CyLee/p/9862384.html
Copyright © 2011-2022 走看看