【问题标题】:Javascript: When and when not to use "this"Javascript:何时以及何时不使用“this”
【发布时间】:2018-02-14 06:26:39
【问题描述】:

我很好奇何时需要/最佳实践使用关键字this。我知道在确定函数this 值时会使用this,但它总是需要吗?

我问的原因是因为我有一个内部函数,它在我的模块中被调用,它所做的只是对你传递的一些数据进行排序。我的问题是我应该使用this 关键字调用这个函数还是单独调用这个函数。

例如:

function formatSomeData(data){
  //code........
}

this.formatSomeData(data);

        OR

formatSomeData(data);

我知道函数被调用的上下文及其目的在回答问题时很重要,但在这种情况下,就像我提到的那样,我真的不需要在任何时候访问 this 对象.调用函数时使用它仍然是一种好习惯吗? 我要问的不是“this”是如何工作的,而是什么时候使用它合适,什么时候不合适。

【问题讨论】:

  • 如果它是某种method,这意味着该函数在某种程度上直接与一个对象相关,那么使用this 是一个很好的设计决策。否则不
  • 顺便说一句 this.formatSomeData(data); 在你的情况下不起作用,所以答案很明显
  • @JonasW。它可能。在非严格模式下,this 将指向window,并且任何不在函数中的声明都将成为全局范围的一部分。
  • @rajesh "in non-strict mode" ...在这里谈论不良做法...

标签: javascript function scope this


【解决方案1】:

在需要/最佳实践时使用关键字 this

这通常在你想访问某些东西时使用。例如,如果您有一个自定义对象并想在某个方法中使用某些属性,您应该使用this

function Person(fname, lname){
  this.fname = fname;
  this.lname = lname;
  this.fullName = function(){
    return this.fname + ' ' + this.lname;
  }
}

var p = new Person('foo', 'bar');
console.log(p.fullName())

如果您看到,在当前构造函数中,我创建了一个函数(fullName),它需要访问它所属对象的fnamelname 属性。这是一个必须使用this 的地方。


现在在声明时,什么时候使用this

构造函数中属于this 的任何属性都将成为对象的一部分。因此,如果您需要只有您自己可以访问但外部无法访问的东西,您可以使用function 而不是this

function Person(fname, lname){
  var self = this;
  self.fname = fname;
  self.lname = lname;
  
  // This function is private
  function getFullName() {
    var name = '';
    var seperator = '';
    if (fname) {
      name += self.fname;
      seperator = ' ';
    }
    if (lname) {
      name += seperator + self.lname;
    }
    return name;
  }
  this.fullName = function(){
    return getFullName();
  }
}

var p = new Person('foo', 'bar');
console.log(p.fullName())

至于您的代码,我已经在评论中解释了它的工作原理:

在非严格模式下,this 将指向window,并且任何不在函数中的声明都将成为全局范围的一部分。

但正如@Jonas W 的正确指针,这是一种不好的做法。为什么不好?

  • 没有声明语句(var|let|const) 定义的任何变量都将成为全局范围的一部分。
  • 声明语句在任何函数之外的任何变量都将成为全局范围的一部分。

【讨论】:

  • 这明确地概括了这一点的技术要点。干得好:)(很高兴提到我)
  • 乔纳斯,谢谢。 @PhilDimeski 很高兴为您提供帮助!
【解决方案2】:

对于刚入门的 JS 开发人员,通过在事件侦听器回调中使用它可能最容易获得 This 的概念。即,“click”事件将 This 绑定到作为目标的对象(如“看,我点击了 THIS!”)。

<ul class="dynamic-list" id="myList">
  <li class="dynamic-list__item">Item 1</li>
  <li class="dynamic-list__item">Item 2</li>
  <li class="dynamic-list__item">Item 3</li>
</ul>

<script type="text/javascript">
  let listItems = document.getElementById("myList").childNodes;
  [...listItems].forEach(function(item) {
    item.addEventListener("click", removeListItem, false);
  })

  // Callback for event, using THIS
  function removeListItem() {
    // Log the text content of <li> to the console. Which one? THIS one.
    console.log(this.textContent);

    // Get the parent of what? Of THIS! And remove its child. Which one? THIS one!          
    this.parentNode.removeChild(this);
  }

</script>

当然,Rajeshs 的答案要复杂得多,但我希望这也能有所帮助……

【讨论】:

    【解决方案3】:

    编程是一种表达事物的方式,以便计算机人类能够理解它们。

    在调用函数时使用它仍然是一种好习惯吗?

    没有确切的答案。你的两个 sn-ps 都可以工作。所以计算机能够理解它。然而,第二个可能会让人类(也就是你的同事)感到困惑:

     this.someFunc();
    

    this 应该指什么?是的,从技术上讲,它指的是window,但从人类的角度来看还不清楚。 这就是为什么在这种情况下我绝对不会提到this。然而,它还有其他很好的用例:

     function changeColor(){
       //When just looking here it makes no sense to refer to this
       this.color = "green";
    }
    
    const car = { color: "grey" };
    
     //But now it makes sense as `this` refers to the `car` it is called on
    car.changeColor = changeColor;
    

    TLDR:使用this 来引用方法/属性,在引用纯函数和变量时不要使用它。

    【讨论】:

      【解决方案4】:

      让我帮你写这段代码吧!

      let emp_detail={
       fname:"jemish",
       lname:"italiya",
       detailStatement:function() {
        return this.fname+" "+this.lname;
        }
      }
      

      让我再举一个例子

      function Data(){
      return this.result
      }
      var a=Data.bind({result:"I am the result!"})();
      console.log(a)    //I am the result!
      

      【讨论】:

        【解决方案5】:

        “This”在函数内部使用,它包含调用该函数的对象的值。

        例如:

        function a(){
         this.newVariable = 'Phil';
        }
        a();
        console.log(newVariable); //This line would display Phil
        

        在这种情况下,即使我们只是在函数 a() 中定义了 newVariable。调用函数的对象是全局对象window,所以'this'指向window,this.newVariable在全局范围内。

        另一个例子是:

        var c={
          log:function(){
            this.name = 'Phil';
           }    
        }
        

        在这种情况下,'this' 指向对象 c,因为日志函数将被 c 调用。

        我们在 Javascript 中使用对象“this”时遇到了更多棘手的情况。这是一篇把握概念的好文章:http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

        【讨论】:

          猜你喜欢
          • 2011-05-15
          • 2018-05-29
          • 2018-11-11
          • 1970-01-01
          • 2012-08-27
          • 2013-01-29
          • 2019-12-15
          • 2020-06-30
          • 1970-01-01
          相关资源
          最近更新 更多