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

前端 未结 7 824
感动是毒
感动是毒 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:53

    I think the unbound 'this' keyword is necessary because JavaScript is a prototype-based language. Someone better informed can probably fill in the details here.

    The fact that it is, is mightily unhelpful though. Especially if you want to pass the method of an object to a higher-order function, things start to get ugly (following examples with a little help from MooTools):

    myArray.each(myObject.foo);
    

    Will not work, because the 'this' in myObject.foo will refer to myArray instead of myObject. Instead:

    myArray.each(myObject.foo.bind(myObject))
    

    Which seems very ugly to me. That's why I usually don't program in an object-oriented way in JavaScript, but I rely heavily on closures instead.

提交回复
热议问题