function expression vs function declaration with regard to javascript 'classes'

故事扮演 提交于 2019-12-11 22:51:27

问题


When does it make sense to use function expressions instead of function declarations when implementing "private methods"? In both cases, the functions are encapsulated, the only practical difference appears to be that I wouldn't be able to call myFunc1 in the constructor. I know I should be using the prototype property either way, but I'm just curious.

function myClass
{
    myFunc1() //error
    myFunc2() //success

    var myFunc1 = function()
    {
    }

    function myFunc2()
    {
    }
}

回答1:


You can call the function assigned to a variable, but you have to assign it before you can call it:

function myClass() {

  var myFunc1 = function() {
  }

  myFunc1() //success
  myFunc2() //success

  function myFunc2() {
  }

}

Those functions are local to the constructor, so it's not the same as using the prototype. To make a public function you need to assign it to the object:

function myClass() {

  this.myPublicFunc1 = function() {
  }

  this.myPublicFunc2 = myFunc2;

  function myFunc2() {
  }

}

var o = new myClass();
o.myPublicFunc1() //success
o.myPublicFunc2() //success



回答2:


You must use an expression if you want to invoke the function immediately.

This one invokes it and assigns the return value to the variable:

function myClass {

    var myVar = function() {
       return 'some value';  // <--- 2. assign the return value to the variable
    }();  // <--- 1. invoke the function immediately

    function myFunc2() {
    }
}

This one invokes it, but assigns the function itself to the variable:

function myClass {

    var myFunc1;

    (myFunc1 = function() {  // <--- 1. assign the function to the variable
       // Do something
    })();  // <--- 2. invoke the function immediately

    function myFunc2() {
    }
}


来源:https://stackoverflow.com/questions/6327213/function-expression-vs-function-declaration-with-regard-to-javascript-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!