代码之家  ›  专栏  ›  技术社区  ›  Lord Grosse Jeanine

调用自对象方法时的最佳实践

  •  0
  • Lord Grosse Jeanine  · 技术社区  · 6 年前

    假设我有这个代码:

    const MyObject = {
        a($els) {
            // What is the best practice here ?
            $els.each(function() {
                MyObject.b($(this));
            });
            // Or
            const self = this;
            $els.each(function() {
                self.b($(this));
            });
        },
        b($el) {
            $el.addClass('test');
        }
    };
    

    在对象中调用另一个方法的“最佳实践”是什么?将变量称为“myObject”有什么缺点吗?还是最好用 this 为什么?

    3 回复  |  直到 6 年前
        1
  •  0
  •   Eriks Klotins    6 年前

    this.method(params)
    

    this var self = this

    const MyObject = {
        a(x) {
            var self = this;
            return x.map(function (a) 
            {
               // cannot use this here to access parent scope
               return self.b(a);
            })
    
    
        },
        b(y) {
          return y % 2;
        }
    

        2
  •  0
  •   KooiInc    6 年前

    this

    const MyObject = {
        getAll: selector => Array.from(document.querySelectorAll(selector)),
        addClass:  (elements, className) => 
          elements.forEach(element => element.classList.add(className)),
    };
    
    MyObject.addClass(MyObject.getAll("[data-test]"), "test");
    setTimeout(() => 
      MyObject.addClass(MyObject.getAll("[data-test2]"), "test2"), 1000);
      
    // using jQuery I'd use
    const MyObjectJQ = {
      setClass4Elements($els) {
        const setClass = this.setClass2Foo;
        $els.each( (i, elem) => setClass($(elem)) );
      },
      setClass2Foo($el) {
        $el.addClass('foo');
      }
    };
    
    setTimeout(() => 
      MyObjectJQ.setClass4Elements($("[data-test2]")), 2000);
    
    // still I'd avoid  the use of [this]
    const MyObjectJQNoThis = {
      setClass4Elements($els, className) {
        const setClass = $el => $el.addClass(className);
        $els.each( (i, elem) => setClass($(elem)) );
      }
    };
    
    setTimeout(() => 
      MyObjectJQNoThis.setClass4Elements($("[data-test]"), "bar"), 3000);
    .test {
      color: red;
    }
    .test2 {
      color: green;
    }
    .foo {
      color: orange;
    }
    .bar {
      color: grey;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div data-test>div1</div>
    <div data-test2>div2</div>
    <div data-test>div3</div>
    <div data-test2>div4</div>
        3
  •  -3
  •   jj anderson    6 年前