Javascript对象内部函数的区别

Max*_*Max 3 javascript

对象中的函数之间有什么区别.我有两个基本上做同样事情的例子.

function a(param) {
   function b(input) {
      return input%10;
   };
return 'The result is ' + b(param);
};
Run Code Online (Sandbox Code Playgroud)

function a(param) {
   this.b=function(input) {
      return input%10;
   };
return 'The result is ' + this.b(param);
};
Run Code Online (Sandbox Code Playgroud)

两种情况下的优点和缺点是什么?在第二个我知道可以从主函数外部调用该函数.运行时还有区别吗?(比如时间和表现)

CMS*_*CMS 11

您必须小心第二个示例,this如果您在没有new运算符的情况下调用函数,关键字将引用Global对象,并且通过查看返回值,您似乎并未尝试创建构造函数.

我想你需要知道this关键字(函数上下文)是如何工作的:

在以下this情况下隐式设置关键字:

1-当函数作为方法调用时(该函数作为对象的成员调用):

obj.method(); // 'this' inside method will refer to obj
Run Code Online (Sandbox Code Playgroud)

2-正常函数调用:

myFunction(); // 'this' inside the function will refer to the Global object
// or 
(function () {})();
Run Code Online (Sandbox Code Playgroud)

3-使用new操作员时:

var obj = new MyObj(); // this will refer to a newly created object.
Run Code Online (Sandbox Code Playgroud)

您还可以使用和方法显式设置this关键字:callapply

function test () {
  alert(this);
}

test.call("Hello world"); // alerts 'Hello world'
Run Code Online (Sandbox Code Playgroud)

现在,b你的两个例子的功能之间的区别,基本上是在第一个片段中,b是一个函数声明,在你的第二个例子中b是一个函数表达式.

函数声明需要提升,它们在分析时进行计算,函数表达式在运行时定义.

如果你想了解函数声明和函数表达式之间差异的更多细节,我给你留下了一些资源:

顺便说一句,在函数声明后你不需要分号.