[英]console.log() an object does not log the method added via prototype in node js console. Or how to print the prototypes also?
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name
}
var tinu = new Person('Tinu');
console.log(tinu.getName()) //Prints the name 'Tinu' - Expected, means the function is added to protoype
console.log(tinu);
最后一个 console.log() 不会通过点原型打印新添加的名为“getName”的方法,只打印属性“name”,在这里我希望在 Person 中打印属性“name”和方法“getName”目的。 以下是上述代码的实际输出和所需输出:
实际产量
蒂努
人{名称:'Tinu'}
期望输出
蒂努
人{名称:'Tinu',getName:[功能]}
下图显示了另一个示例,其中通过原型添加的方法“getFullName”在打印以控制台添加它的对象时正确显示。 并期望与我的示例相同
console.log
是您的 js 环境(在您的情况下为 Node.js)提供的 API。 没有标准规格。 因此,在您的情况下, console.log
打印您的 Javascript 对象的简单字符串表示形式。
{ propName: propValue }
在Node.js 中有一个 util-module ( util-documentation )。 此外,我找到了一个方法,它返回一个对象的所有属性,包括原型链的所有属性。
const util = require('util')
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name
}
var tinu = new Person('Tinu');
console.log(util.inspect(tinu, {showHidden: false, depth: null}))
function getAllPropertyNames(obj) {
var props = [];
do {
Object.getOwnPropertyNames(obj).forEach(function (prop) {
if (props.indexOf(prop) === -1 ) {
props.push( prop );
}
});
} while (obj = Object.getPrototypeOf(obj));
return props;
}
console.log(getAllPropertyNames(tinu));
/*
[ 'name',
'constructor',
'getName',
'__defineGetter__',
'__defineSetter__',
'hasOwnProperty',
'__lookupGetter__',
'__lookupSetter__',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'valueOf',
'__proto__',
'toLocaleString' ]
*/
如果您在浏览器上并想查看定义的方法和其他信息,您可以使用浏览器的开发人员工具。 按F12
,你可以做很多调查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.