-1

I am learning javascript and my current understanding is the main way javascript uses for scoping is the function scope, and there are no block scopes in general.

So I came up with this:

var obj = {
  foo: function myfunc() {
    console.log("123");
  }
};

myfunc();

I thought because javascript doesn't have block scoping, the definition of myfunc() will be visible in global scope. But it actually did not. Can someone help to explain this?

shengy
  • 8,380
  • 3
  • 33
  • 61

1 Answers1

2

There are three points where your understanding is flawed:

  • JavaScript does have block scopes since ES6.
  • Object literals are no blocks, they do not introduce any scopes.
  • Your function is not becoming a global because it is not a declaration (which is syntactically invalid inside an object), but a function expression that just creates a named function object which then is assigned to the foo property of the newly created object. See var functionName = function() {} vs function functionName() {} for details.
Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • 2
    @shengy: The downvote means "*This question does not show any research effort; it is unclear or not useful*". – Bergi Jun 17 '16 at 16:02