What is the rationale for the behavior of the 'this' keyword in JavaScript?

前端 未结 7 817
感动是毒
感动是毒 2020-12-13 00:59

I am asking this from a language design point of view. So I am trying to find out

  1. What is the rationale for the behavior of this?
  2. To what
7条回答
  •  离开以前
    2020-12-13 01:51

    I think unbound "this" is a mistake. Otherwise it is quite handy. Unbound "this" opens the possibility of misinterpreting the context most prominently apparent in event handling of browsers. Also javascript libraries have different opinions of what "this" should refer to in event handling and many callback constructs (like map, filter).

    Removing unbound "this" probably wouldn't make things any more difficult.

    Edit: I guess an alternative syntax example will make my stance clearer.

    function Foo()
    {
        //both this refer to the Foo instance
        this.blah=this.function(){this.bar;};
    
        //second this refers to baz
        this.blah=baz.function(){this.bar;};
    
        //second this refers to anonymous function itself
        this.blah=function(){this.bar;};
    }
    

提交回复
热议问题