-1
var chapter = {
    num: 7,
    title: ‘Creating Functions’,
    getNum: function() { return num; }\\without this keyword
};

the output is undefined without the keyword this

var chapter = {
    num: 7,
    title: ‘Creating Functions’,
    getNum: function() { return this.num; }\\with this keyword
};

why does it need this keyword pls explain it in simple way. this is question is repeated i know but i saw them all never satisfied. so pls....

and one thing more what actually this code do.

(function() {
    // Function body goes here.
})();

i know a bit that its immediately invoked function but i need some detail explanation . thank u all in advance

  • 1
    this tells it to access the variable within the object not a global variable. i.e. the variable belonging to chapter object. – Jon Taylor Jan 30 '13 at 11:46
  • Read some documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this. – Felix Kling Jan 30 '13 at 12:54

2 Answers2

2

num is the variable num in the current scope (which is determined by where a function is defined).

this.num is the property num on the current context (which is determined by how a function is called).

immediately invoked function but i need some detail explanation

Scope in JavaScript is determined by functions. Immediately invoked functions create a new scope and are used to avoid adding extra variables to the current scope.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • It's probably a language design choice, it would have been possible to have it implicitly be `this.num`, when it would otherwise be a `ReferenceError` but that would make for much harder debugging of typos – Esailija Jan 30 '13 at 11:49
0

To answer the last part of you question: that 'trick' is called a closure.

Firstly: (...)() creates something inside the first set of parentheses and then calls the result of that. If we put a function in place of ..., it will call that function.

The reason someone would do this, is to create a scope that allows one to define all kinds of things without polluting the global scope (just putting var myVar = 1; somewhere will assign the variable to the global scope. Within a closure, you're free to make all the mess you want without turning the global scope into a mess for any other script.

akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
  • No, the function is not necessarily intended to be a closures. The "trick" is that the function is called immediately which creates a new scope. Some people call it [**IIFE**](http://benalman.com/news/2010/11/immediately-invoked-function-expression/). Whether the function is used as a closure or not is irrelevant. – Felix Kling Jan 30 '13 at 12:57