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

后端 未结 5 2141
难免孤独
难免孤独 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条回答
  •  猫巷女王i
    2021-02-18 13:32

    There are two main problems

    1. The MIME type is text/javascript, not text/jscript
    2. You are defining the method after you try to call it

    So:

      function MyObject() {
        this.MyMethod = function () {
          alert('It works');
        }
        this.MyMethod(); //should now work
      }
    
      var test = new MyObject();
    

提交回复
热议问题