如何覆盖javascript类中的var?

plo*_*uzz 0 javascript jquery

我学会创建自己的库.这对我来说是新的.我开始学习这个库,如果你看到,我有类似的clear function库,但我的代码没有替换var history.

初始值: var history = [];

显示():返回 []

添加('asd'): history[0] = 'asd';

显示():返回 [asd]

清除:将var历史记录恢复为空 var history = []

Show():返回[asd]我的期望[]

这是我的代码:

;(function() {
  'use strict';
  var testLib = function() {
    var index = -1,
      history = [];
    return {
      add: function(data) {
        history[history.length] = data;
      },
      show: function() {
        return history;
      },
      clear: function() {
        var index = -1,
          history = [];
      }
    };
  };

  window.testLib = testLib;
}());

$(function() {
  var mylib = new testLib();
  mylib.add('asdasd');
  console.log(mylib.show());
  mylib.clear();
  console.log(mylib.show()); //expect: [] empty array
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Run Code Online (Sandbox Code Playgroud)

Der*_*會功夫 5

只需删除var您的clear方法:

clear: function() {
    index = -1;
    history = [];
}
Run Code Online (Sandbox Code Playgroud)

您正在声明新变量,而不是修改闭包中的变量.在现代ECMAScript中,您可能需要考虑将库创建为"类":

class History{
    // ...
    clear() {
        this.history = [];
        this.index = -1;
    }
}
Run Code Online (Sandbox Code Playgroud)