gpt4 book ai didi

javascript - 如何在 JavaScript 中从现有对象的构造函数创建新对象

转载 作者:行者123 更新时间:2023-11-28 20:26:38 25 4
gpt4 key购买 nike

考虑以下 JavaScript 代码:

if (oo instanceof MyType) {
var newObj = new oo.constructor;

// suppose the following check should be ok but it is not
// newObj should have same constructor as its original oo.

if (newObj instanceof MyType) {
// do something
}
}

我无法达到“做某事”。怎么了?

最佳答案

好吧,只是因为您可能没有阅读注释,所以您在 constructor 中出现了拼写错误(它说 contractor)。

这有效:

function MyType() {}
oo = new MyType();

if(oo instanceof MyType)
{
var newObj = new oo.constructor(); // The mistake was in this line

if( newObj instanceof MyType)
{
console.log("a contractor was killed by a constrictor while constructing");
}
}

关于javascript - 如何在 JavaScript 中从现有对象的构造函数创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17267929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com