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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…