zoukankan      html  css  js  c++  java
  • 私有变量和特权方法

    1.定义

    私有变量:js的作用域属于函数作用域 ,外部变量不能访问函数内部定义的变量  ,此变量为私有变量

    特权方法:有权访问内部私有变量和方法的公有方法

    2.定义对象的方式

    一是使用Object实例化或者对象表达式 

    var TaoBao = (function() {

    // 私有属性 var _total = 10;

    // 私有方法var _buyFood = function() { _total--; };

    var _getTotal = function() { return _total; }

    return { name: 'taobao', getTotal: _getTotal,

    //使用了闭包的方式来间接使用内部私有变量

    buy: _buyFood } }) ();

    TaoBao.buy(); console.log(TaoBao.name); // 'taobao'

    console.log(TaoBao.getTotal()); // 9

    二是使用构造函数。

    function TaoBao(name) {

    // 私有属性 var _total = 10;

    // 公有属性 this.name = name;

    // 私有方法 function _buyFood() { _total--; }

    // 特权方法,才能访问私有的属性和私有的方法 this.buy = function() { _buyFood(); }

    this.getTotal = function() { return _total; } }

    // 公有方法, 注意这里不能访问私有成员_total TaoBao.prototype.getName = function() { //console.log(_total); // Uncaught ReferenceError: _total is not defined return this.name; } var taobao = new TaoBao('taobao'); console.log(taobao.getName()); // 'taobao' taobao.buy(); console.log(taobao.getTotal()); // 9

    三合二为一

     var TaoBao = (function() {

    // 私有属性 var _total = 10; // 私有方法

    function _buyFood() { _total--; } // 构造函数

    function TaoBao(name) {

    this.name = name;

    this.getTotal = function() { return _total; } }

    //这里怎么可以访问私有的方法??这里不是TaoBao内部的私有哦!

    TaoBao.prototype.buy = function() {

    console.log(_total); // 10

    _buyFood(); }

    TaoBao.prototype.getName = function() { return this.name; }

    return TaoBao; }) ();

    var taobao = new TaoBao('taobao');

    console.log(taobao.getName()); // 'taobao'

    taobao.buy(); console.log(taobao.getTotal()); // 9

  • 相关阅读:
    Spring MVC 完全注解方式配置web项目
    spring WebServiceTemplate 调用 axis1.4 发布的webservice
    修改Intellij Idea 创建maven项目默认Java编译版本
    Git Commit提交规范和IDEA插件Git Commit Template的使用
    myEclipse10安装以及破解
    ES6中Map与其他数据结构的互相转换
    ES6用来判断数值的相关函数
    WebStorm使用码云插件问题
    Css解决表格超出部分用省略号显示
    Js/Jquery获取网页屏幕可见区域高度
  • 原文地址:https://www.cnblogs.com/theworldofbeisong/p/9027900.html
Copyright © 2011-2022 走看看