new ObjectId() 和 new ObjectId 和 ObjectId() 有什么区别?

4

假设我在文件开头有这个定义:

const ObjectId = mongoose.Types.ObjectId;

你应该选择哪一个并为什么呢?
// 1 
new ObjectId;  

// 2
new ObjectId();

// 3
ObjectId();

官方文件建议使用new ObjectId。对我来说,new ObjectId() 更自然,但它们都会生成一个新的ObjectId,并且我已经在SO的问题和答案中看到了每种方法的例子。
引用: http://mongoosejs.com/docs/api.html#types-objectid-js 更新:
让我澄清一下:我知道如何在JavaScript中使用new运算符,并想找出在生成ObjectID时使用new是否有任何重大区别。(函数行为不同、抛出错误等)

1
MDNnew 运算符有很好的解释(以及为什么如果你不使用它调用构造函数,它们很可能会表现得有点奇怪)。 - Joe Clay
1个回答

6

这些实例之间绝对没有任何区别。让我逐个解释每种方式的工作原理:

  • new ObjectId - This is completely fine and does the same thing as new ObjectId(); because you can instantiate without parentheses if the constructor does not take any arguments, see the MDN documentation on the new operator

  • new ObjectId() - This is the "standard" way to instantiate an object and is equivalent to new ObjectId

  • ObjectId() - This is the exact same as the above two. This is because of the line in the source code:

    if(!(this instanceof ObjectID)) return new ObjectID(id);
    

    The above code does the following:

    a. !(this instanceof ObjectID) - Checks if this is an instance of ObjectID. This is only true if the constructor is called with new where this will refer to the current instance, or else this will be window or undefined depending on if you are in strict mode.

    b. return new ObjectID(id) - If the constructor is not called with new, then the function will return new ObjectID(id). That means if you call ObjectId() in your example, the function will detect this and return new ObjectID(id) (or if id is not given, new ObjectID()) so it is exactly the same as the above two options.

总之,功能上没有区别,只取决于你喜欢如何编写。在功能上没有理由更喜欢其中一个。
注意:ObjectIDObjectId是同一件事情。源代码说明:var ObjectId = ObjectID;

感谢您详细阐述。在测试Node.JS中的mongodb时,唯一无效的事情是ObjectId无效。 "mongodb": "^2.2.30"这里的mongodb包只接受ObjectID(大写字母ID):否则您可能会收到此错误:node_modules\mongodb\lib\mongo_client.js:429 throw err ReferenceError: ObjectId is not defined。正如您所说,两种语法都可以使用ObjectID()new ObjectID() - Junior Mayhé
@JuniorM 我在谈论 Mongoose,而不是一般的 MongoDB。Mongoose 公开了 ObjectId 和 ObjectID。 - Andrew Li

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接