简体   繁体   中英

why "fucntion body" is returned instead of "function object" when we console log a function?

I have an object "person1" and in it, there is a method "enroll" ==>

 function Person(first, last, age, gender) { this.enroll = function abc() { console.log("hello world") } // property and method definitions this.name = { first: first, last: last, }; this.age = age; this.gender = gender; //...see link in summary above for full definition } let person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']); console.log(person1);

My question is why on console.log(person1.enroll) function body or function definition(ƒ abc() {console.log("hello world")}) is returned, why the whole function object is not returned like this =>

ƒ abc()
    arguments: null
    caller: null
    length: 0
    name: "abc"
    prototype: {constructor: ƒ}
    [[FunctionLocation]]: oop2.html:12
    [[Prototype]]: ƒ ()
    [[Scopes]]: Scopes[2]

and why do I have to do console.dir(person1.enroll) to see all properties and methods of enroll function object. Why console.log(person1.enroll) does not give access to all methods and properties inside of enroll function.

The answer to why does log produce what it does and dir produce what it does is that they are written for a particular reason. According to the documentation

The intent behind log is "for general output of logging information"

The intent behind dir is to "display an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects."

So by intent, log does not give you all the properties and methods and other information. log is just for "general logging," to give you some hint about the object. We have dir for the express purpose of outputting everything. In other words log doesn't give you a detailed description because the designers of the console object chose to put that information in dir .

(The designers could have chosen to output more with log but they wanted to reserve that more powerful feature for dir . Besides you are probably familiar with out console dot logging general object gives the often useless [object Object] so it should not really be a surprise that logging a function does not give full details either.)

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