Javascript - How do you call a function inside a class from within that class?

后端 未结 5 2113
难免孤独
难免孤独 2021-02-18 13:25

I am trying to call the function MyMethod from within a object but none of the syntax below works. There must be a really obvious error below but I can\'t see it.



        
5条回答
  •  北海茫月
    2021-02-18 13:45

    The 2 ways of defining a function provide different accessibilities

    First, setting it a property of the parent function, as is done in the "A" version of your script below. If you do this, the function is only usable after you give the definition.

    Second, defining the function with the classical approach of "function functionName () { ... }". This definition undergoes "hoisting", which means the function becomes available throughout the parent object, i.e. even above the place it is defined. You can see this in the "B" version in the sample below, based on the original poster's code. Also on https://jsfiddle.net/dnL4j30u/

    
    

    The output is

     It works B       (this works because the second definition gets hoisted)
     It works A
     It works B
    

提交回复
热议问题