How to explain 'this' keyword in a best and simple way?

前端 未结 6 2185
别那么骄傲
别那么骄傲 2020-12-06 19:40

I am using \'this\' keyword for a long time. But when someone asks me to explain it, I am confused that how to explain it. I know that I can use this in a method of class to

6条回答
  •  北海茫月
    2020-12-06 20:34

    Like their name suggests, instance methods operate on instances of a class. How do they know which one to operate on? That's what the this parameter is for.

    When you invoke an instance method, you're really invisibly passing in an extra parameter: the object to invoke it on. For example, when you have this:

    class Basket {
      public function a() {
        $this-> ...;
        // ...
      }
      // ...
    }
    

    and you call $some_basket->a(), behind the scenes you're actually calling something like Basket::a($some_basket). Now a() knows which Basket you want to work with. That special parameter is what this refers to: the current object you're dealing with.

提交回复
热议问题