& # 39;这个# 39;ES6和Knockout的作用域

'this' scope with ES6 and Knockout

本文关键字:作用域 Knockout 这个 ES6      更新时间:2023-09-26

我在使用ES6时遇到了'this'作用域的问题。

这是我用BabelJS编译的原始代码的链接。

当调用函数从数组中移除一个元素时,'this'的作用域是未定义的。

如何在不重新定义这个的情况下使这个变成这个(let self = this)?

"use strict";
var _createClass = (function() {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  return function(Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
})();
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
var Point = (function() {
  function Point() {
    var _this = this;
    _classCallCheck(this, Point);
    this.myArray = ko.observableArray([1, 2, 3, 4]);
    this.removeFromArrayWithArrowFunction = function(value) {
      _this.myArray.remove(value);
    };
  }
  _createClass(Point, [{
    key: "removeFromArray",
    value: function removeFromArray(value) {
      this.myArray.remove(value);
    }
  }]);
  return Point;
})();
ko.applyBindings(new Point());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-bind="text: ko.toJSON(myArray)"></span>
<h2>Issues with this scoping when using a regular Function</h2>
<ul data-bind="foreach: myArray">
  <li>
    <a href="#" data-bind="text: $data, click: $parent.removeFromArray"></a>
  </li>
</ul>
<h2>Works as expected using an arrow function</h2>
<ul data-bind="foreach: myArray">
  <li>
    <a href="#" data-bind="text: $data, click: $parent.removeFromArrayWithArrowFunction"></a>
  </li>
</ul>

如果在绑定中直接使用视图模型函数,就会失去this的上下文,就像Jeff Mercado解释的那样。箭头函数捕获封闭上下文的this值,因此如果您使用箭头函数表示法,则不必担心var self = this

那么修改如下:

removeFromArray(value) {
  this.myArray.remove(value);
}

为:

removeFromArray = (value) => {
  this.myArray.remove(value);
}

应该没问题。

看到巴别塔