开发者

Javascript difference between functions within an object

开发者 https://www.devze.com 2022-12-16 03:25 出处:网络
What is the difference be开发者_开发问答tween functions within an object. I have 2 examples which basically do the same thing.

What is the difference be开发者_开发问答tween functions within an object. I have 2 examples which basically do the same thing.

function a(param) {
   function b(input) {
      return input%10;
   };
return 'The result is ' + b(param);
};

and

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

What is the advantage and the disadvatages in both cases? In the second i know that that function can be called from outside the main function. Is there also a difference when running it? (like time and performance)


You have to be careful with the second example, the this keyword will refer to the Global object if you invoke the function without the new operator, and by looking at your return value, seems that you aren't trying to make a constructor function.

I think you need to know how the this keyword (the function context) works:

The this keyword is implicitly set when:

1- When a function is called as a method (the function is invoked as member of an object):

obj.method(); // 'this' inside method will refer to obj

2- A normal function call:

myFunction(); // 'this' inside the function will refer to the Global object
// or 
(function () {})();

3- When the new operator is used:

var obj = new MyObj(); // this will refer to a newly created object.

And you can also set the this keyword explicitly, with the call and apply methods:

function test () {
  alert(this);
}

test.call("Hello world"); // alerts 'Hello world'

Now, the difference between the b function of your two examples, is basically that in the first snippet, b is a function declaration, in your second example b is a function expression.

Function declaration are subject to hoisting, and they are evaluated at parse time, on function expressions are defined at run-time.

If you want more details of the differences between function declarations and function expressions, I leave you some resources:

  • Explain JavaScript's Encapsulated Anonymous Function Ssyntax
  • Named function expressions demystified

And BTW, you don't need the semicolon after function declarations.

0

精彩评论

暂无评论...
验证码 换一张
取 消