Javascript difference between functions inside an object

What is the difference between functions inside an object. I have 2 examples that 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 are the advantages and disadvantages in both cases? In the second, I know that this function can be called from outside the main function. Is there any difference at startup? (e.g. time and performance)

+3
source share
1 answer

You should be careful with the second example, the keyword thiswill refer to the Global object if you call the function without an operator new, and, looking at your return value, it seems that you are not trying to make a constructor constructor .

, , this ( ):

this , :

1- ( ):

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

2- :

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

3- new:

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

this , call apply :

function test () {
  alert(this);
}

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

b , b , b .

hoisting, , .

, :

BTW, .

+11

Source: https://habr.com/ru/post/1727985/


All Articles