函数表达式与函数声明关于javascript'classes' [英] function expression vs function declaration with regard to javascript 'classes'

查看:90
本文介绍了函数表达式与函数声明关于javascript'classes'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现私有方法时,什么时候使用函数表达式而不是函数声明是有意义的?在这两种情况下,函数都被封装,唯一的实际差异似乎是我不能在构造函数中调用myFunc1。我知道我应该使用原型属性,但我只是好奇。

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()
    {
    }
}


推荐答案

您可以调用分配给变量的函数,但必须先分配它,然后才能调用它:

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

这篇关于函数表达式与函数声明关于javascript'classes'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆