在Javascript中,有没有一种多态设置方法

时间:2019-07-18 15:37:13

标签: javascript polymorphism closures setter

背景:库对象具有旨在用作方法的属性,但程序员经常错误地将其作为属性访问-> 例如预期的界面:

this.filter(function(){...});

通常被错误地用作

this.filter=function(){...};

,它当然会覆盖该方法。 (哎哟)。

应对这种情况的第一个尝试是通过改变

this.filter = function(implementation) {
              this.format = implementation;
              this.isfilter = true;
              }

Object.defineProperty(this, "filter", {
    get:  function() { return this.format; },
    set:  function(implementation) {
              this.format = implementation;
              this.isfilter = true;
              }
    });

对于错误的用例来说,这是件好事(this.filter = ...) 但当然是第一个(预期的情况是this.filter(function(){})) 不能再工作了。

在这种情况下,有什么办法可以实现多态?即同时处理 情况-a)不删除现有代码,并且b)要么,1)处理该分配,或者针对滥用情况发出警告/例外? 还是有一些关闭魔术可以做到这一点?

1 个答案:

答案 0 :(得分:0)

这当然可以做到。

通过仅用get属性替换该方法,将返回一个函数。

使用ES2015类:

class Filterable {
    get filter() {
        return (implementation) => {
            this.format = implementation;
            this.isfilter = true;
        }
    }
}

请注意,没有属性设置器。

尝试分配给该属性将失败,并在严格模式下抛出错误(始终使用严格模式!)

示例:

"use strict";

class Filterable {
  get filter() {
    return (implementation) => {
      this.format = implementation;
      this.isfilter = true;
    }
  }
}

const filterable = new Filterable();

filterable.filter(function (){}); // OK

filterable.filter = function () {}; // Error

当然,您不需要为此使用ES2015类,它将在您使用过它时与define属性一起使用。

Object.defineProperty(this, "filter", {
    get: function () {
      return function(implementation) {
        this.format = implementation;
        this.isfilter = true;
      };
    }
});
相关问题