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

时间:2013-06-24 04:14:03

标签: javascript

考虑以下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
    }
}

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

1 个答案:

答案 0 :(得分:3)

好吧,只是因为你可能没有阅读评论,你在constructor中有一个拼写错误(它显示为constractor)。

这有效:

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