如何处理没有构造函数的JavaScript对象 [英] How to deal with JavaScript Objects which have no constructor

查看:149
本文介绍了如何处理没有构造函数的JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Node.js querystring.parse()方法返回看起来像是一个对象的东西,但是没有构造函数的东西。根据 https://nodejs.org/api/querystring.html

Node.js querystring.parse() method returns what looks like to be an object, but one without a constructor. According to https://nodejs.org/api/querystring.html :

... querystring.parse()方法返回的对象不是原型继承自JavaScript对象。这意味着典型的Object方法,如obj.toString(),obj .hasOwnProperty()和其他人没有定义,也无法工作。

"... The object returned by the querystring.parse() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work."

这很容易导致错误,因为通常你会假设每个Object都理解一些基本方法,比如toString(),并且它有一个或多或少告诉我们它的构造函数 类型。

This easily causes bugs because typically you would assume that every Object understands some basic methods like toString() and that it has a "constructor" which more or less tells us its "type".

处理这些相当无能为力的对象的最佳方法是什么?我试过了:

What's the best way to handle these rather incapable Objects? I tried:

let myOb =  new Object(dumbObject);

但是这会产生一个没有toString() - 方法的结果,并且没有财产'建设者'。

But that produces a result which does not have the toString() -method either and does not have the property 'constructor'.

将这些愚蠢的物体变成通常表现的物体的最佳方法是什么?而且,为什么有人想在第一时间创建这样的对象?

What's the best way to turn these dumb objects into ordinarily behaving ones? And, why would anybody want to create such objects in the first place?

推荐答案

我想(从我的头脑中)

I think (from the top of my head)

让newObject = JSON.parse(JSON.stringify(dumbObject))

let newObject = JSON.parse(JSON.stringify(dumbObject))

应该有效。

这篇关于如何处理没有构造函数的JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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