Functions inside objects

后端 未结 2 1942
渐次进展
渐次进展 2020-12-14 15:52

I know the title is vague but I didn\'t know what to write.
In javascript, I know how to write functions that will be called like this :

argument1.func         


        
相关标签:
2条回答
  • 2020-12-14 16:25

    you need to define the objects like this :

    var argument1 = {
        myvar : "12",
        mymethod : function(test) { return something; }
    }
    

    then call mymethod like:

    argument1.mymethod(parameter);
    

    or the deeper version :

    var argument1 = {
        argument2 : {
           mymethod : function(test) { return something; }
        }
    } 
    

    then:

    argument1.argument2.mymethod(parameter);
    
    0 讨论(0)
  • 2020-12-14 16:45

    Modern ES6 Approach

    You no longer need to specify the function keyword when defining functions inside objects:

    var myObj = {
      myMethod(params) {
        // ...do something here
      },
      myOtherMethod(params) {
        // ...do something here
      },
      nestedObj: {
        myNestedMethod(params) {
          // ...do something here
        }
      }
    };
    

    Equivalent except repetitive and verbose:

    var myObj = {
      myMethod: function myMethod(params) {
        // ...do something here
      },
      myOtherMethod: function myOtherMethod(params) {
        // ...do something here
      },
      nestedObj: {
        myNestedMethod: function myNestedMethod(params) {
          // ...do something here
        }
      }
    }; 
    
    0 讨论(0)
提交回复
热议问题