简体   繁体   中英

Why does functions in class and function have different expression when I log them in javascript?

I made Example function and Example2 class. I expected log results will be the same. But they are actually not exactly same.

 function Example() {} Example.prototype.ex = function () {}; Example.iex = function () {}; console.log(Example.prototype.ex); console.log(Example.iex); class Example2 { ex() {} static iex() {} } console.log(Example2.prototype.ex); console.log(Example2.iex);

The log results of code above is..

[Function]
[Function]
[Function: ex]
[Function: iex]

functions from class shows [Function: name] . But functions from function shows only [Function] without the name of function.

When you use method syntax inside a class or an object literal - that is, when the function looks like

functionName() {
}

The interpreter will automatically assign that function the name of the property. In contrast, when you have an unnamed function expression , like with:

someObj.someFn = function () {};
//               ^^^^ this function expression isn't named

The function does not receive a name property. After all, just from

function () {}

there isn't any name that could be meaningfully given to it.

(When assigned to a standalone variable like const fn = , the function will receive the name of the variable, but this does not occur when assigning to a property to an object.)

Functions with a name property, when logged, will show their name. Functions without a name property won't show their name.

 const obj = {}; obj.unnamedFn = function() {}; const obj2 = { namedFn() {} }; console.log(obj.unnamedFn.name); console.log(obj2.namedFn.name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM