JavaScript - function as an object property

后端 未结 3 1389
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 05:52

Hey everyone, this is #23 from John Resig Advanced JavaScript http://ejohn.org/apps/learn/#23, called

What happens if a function is an object pr

相关标签:
3条回答
  • 2021-02-01 06:26

    1) Katana is an object. Katana.use is a function. Its a property that contains a function as value. The value it contains happens to be an anonymous function.

    The distinction is that Katana.use is a property of Katana and that the value of Katana.use is a function. use is a key defined on Katana since Katana["use"] also works.

    2) It's setting isSharp to NOT isSharp so either true -> false or false -> true

    3) the assert is saying katana.isSharp === false which it should be since it was orginally true but then set to false.

    0 讨论(0)
  • 2021-02-01 06:31
    1. Yes, katana is an object (created using the { ... } notation). "use" is the name of the property of the object whose value will be the anonymous function (which is also an object).

    2. The function inverts the value of isSharp (so from true to false or false to true).

    3. It is asserting that isSharp is something which does not evaluate to true (this is nearly everything except undefined, null, false, 0, etc). In this case, since isSharp is always either true or false, it is asserting that it is false.

    The main point (and cool part) of the sample is this line:

    katana.use();
    

    This first fetches the value of the "use" property from the katana object (that's the katana.use part). The value is the anonymous function from before. Then, that function is executed (that's the () part). The really cool part is that it is executed on behalf of the katana object -- that means this in the anonymous function is a reference to the katana object when it's called that way.

    0 讨论(0)
  • 2021-02-01 06:37
    1. use is a property of the object katana.
    2. !this.isSharp will negate the value of this.isSharp. Ex if isSharp is true it will return false else it return false.
    3. The assert checks whether the result of the boolean result is true. If the result is false then the assertion fails.
    0 讨论(0)
提交回复
热议问题