为什么console.log显示不同的描述

时间:2018-03-18 22:12:02

标签: javascript node.js function declaration

我在节点中运行以下命令:为什么第一个console.log显示:

greet: [Function],

和第二个console.log显示:

greet: [Function: greet]

有什么区别吗? (注意,chrome中的console.log没有显示差异)

function deepCopy(obj){

/* an object has key value pairs
   check if val is object
   if true deepCopy(val)
   else return value            */

   const keys = Object.keys(obj); // gets keys of object
   const newObject = {}

   for(index in keys){
      if(typeof(obj[keys[index]]) === 'object') {
		  newObject[keys[index]] = deepCopy(obj[keys[index]])
      }else{
		  newObject[keys[index]] = obj[keys[index]]
      }
  }
   return newObject
}

o={
name:'David',
teach:true,
obj:{
     greet:function(){
           console.log('hi!')},
     last:'cross'
    }
}



o2 = deepCopy(o)


o.obj.greet=function(){
	    console.log('bye')}


o.name='george'

console.log(o)
console.log(o2)

o.obj.greet()
o2.obj.greet()

1 个答案:

答案 0 :(得分:0)

  1. 当您声明方法{ great:function(){} }时,它将有一个.name,并将由console.log打印出来。即使你传递它(通过o2分配给deepCopy),也会保留它的名称。
  2. 当您创建匿名函数function(){}时,它的.name为空。您将其分配给o.great = function(){}
  3. 我创建了一个简化版本来解释运行问题以进行测试。

    const a = { great: function(){}  }; // in object declaration, method great as name "great" (x)
    const b = {};
    b.great = function(){}; // b.great is point to an anonymous function with no name (y)
    // When console.log a function, if function has name, it will show out
    console.log("a.great", a.great);
    console.log("b.great", b.great);
    console.log("a.great.name", JSON.stringify(a.great.name)); // "great"
    console.log("b.great.name", JSON.stringify(b.great.name)); // "";
    
    b.great = a.great; // simliar when you deep copy o2 from o
    // in this case, b.great is point to the method great (x)
    // so when you log out the name, it will print out
    console.log("b.great.name", JSON.stringify(b.great.name)); // "great"
    
    a.great = function(){}; // similar when o.great get re-assign
    // a.great got re-assign to an anonymous function with no name (z)
    // so when you log out the name, it will print out ""
    console.log("a.great.name", JSON.stringify(a.great.name)); // ""
    
    // Finally:
    console.log(a.great);
    console.log(b.great);