【问题标题】:console.log a javascript Object/Class - same result before and after the change of the prototypeconsole.log 一个 javascript 对象/类 - 原型更​​改前后的结果相同
【发布时间】:2014-04-04 11:54:56
【问题描述】:

我正在尝试了解 js prototypesclasses 的工作原理,我正在使用 Chrome 的 console.log 在添加新属性等时打印并查看对象的状态。

这是我正在使用的代码:(fiddle)

function Person(){}

Person.prototype.sayHello = function(){ alert("Hello"); };
Person.prototype.name = "Name";

console.log(Person.prototype) //1st console.log

Person.prototype.surname = "Surname";

console.log(Person.prototype); //2nd console.log

我希望在控制台中打印两个不同的结果,因为surname 属性是在第一个控制台日志之后添加的。相反,这是控制台输出:

如您所见,两个输出都定义了 surname 属性,即使它仅在第一个 console.log 之后添加..

你能解释一下为什么吗?我错过了什么?调用时console.log不显示对象的当前状态吗?

提前谢谢你,最好的问候

【问题讨论】:

    标签: javascript prototype console.log


    【解决方案1】:

    您设置人员姓氏的下一行代码,不等待控制台日志,因为 console.log 是异步的,当您超时尝试此代码时,它将是正确的,

     function Person() {}
    
     Person.prototype.sayHello = function () {
         alert("Hello");
     };
     Person.prototype.name = "Name";
    
     console.log(Person.prototype) //1st console.log
     setTimeout(function(){
      Person.prototype.surname = "Surname";
    
     console.log(Person.prototype); //2nd console.log
     },1000);
    

    您可以在记录之前保存该对象的副本,然后它会起作用

    Synchronous console logging in Chrome

    更新: 我有一个更好的解决方案:
    只需记录对象的字符串化版本就可以了

    console.log(JSON.stringify(Person.prototype))
    

    【讨论】:

    • 看看这个this 小提琴:如果你在打开对象层次结构之前等待console.log,hte surname 存在于两者中......如果你打开第一个对象同时等待第二个日志,surname 未显示.. 为什么:O?
    • hmn for me "surname" 仅出现在 mac osx 上最新 chrome 的第二次登录中
    • 如果您等待第二个日志出现然后(并且只有那时)您打开 Person 对象?
    • 正如我所说,您可以只复制对象并记录复制的实例,但是是的,这很奇怪:D
    • “你设置姓氏的下一行代码,不会等待控制台日志,因为 console.log 是异步的” 不,console.log 不是异步的。但是控制台保持对对象的实时引用,并且在控制台中扩展对象是异步的。有时。取决于您登录时控制台是否打开等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2021-01-22
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多