console.log一个javascript对象/类-更改原型前后的结果相同 [英] console.log a javascript Object/Class - same result before and after the change of the prototype

查看:90
本文介绍了console.log一个javascript对象/类-更改原型前后的结果相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 js原型的工作方式,并且我使用的是Chrome的 console.log 打印并查看对象的状态,同时添加新属性等。



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



更新:
i有一个更好的解决方案:

只需记录对象的字符串化版本,就可以了

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


I'm trying to understand how js prototypes and classes work, and I'm using Chrome's console.log to print and have a look at the state of my objects while I add new properties etc.

This is the code I'm using: (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

I expect to have two different results printed in the console, because the surname property was added after the first console log. Instead, this is the console output:

As you can see, both the outputs have the surname property defined even if it was added only after the 1st console.log..

Can you explain me why? What am I missing? Doesn't console.log show the current state of the object when called?

Thank you in advance, best regards

解决方案

your next line of code where you set the persons surname, doesnt wait for the console log because console.log is asynchrounous, when you try out this code with a timeout it will be correct,

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

you could save a copy of that object before you log it, then it would work

Synchronous console logging in Chrome

UPDATE: i have an even better solution :
just log a stringifyed version of the object and you´ll be okay

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

这篇关于console.log一个javascript对象/类-更改原型前后的结果相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆