Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...