gpt4 book ai didi

javascript - 如果 Crockford 建议我们将它用于原型(prototype)继承,为什么他说不要使用 new 关键字?

转载 作者:可可西里 更新时间:2023-11-01 01:33:31 25 4
gpt4 key购买 nike

我看过一段视频,其中 Crockford 告诉我们不要使用 new 关键字。如果我没记错的话,他说要改用 Object.create 。为什么他告诉我们不要使用 new,如果他在他写的这篇文章中使用它来实现原型(prototype)继承:http://javascript.crockford.com/prototypal.html

我希望他使用 Object.create 而不是 new,如下所示:

function object(o) {
return Object.create((function() {}).prototype = o);
}

那为什么他还在用new呢?

最佳答案

Crockford 在 this Nov 2008 message to the JSLint.com mailing list 中讨论了 newObject.create .摘录:

If you call a constructor function without the new prefix, instead of creating and initializing a new object, you will be damaging the global object. There is no compile time warning and no runtime warning. This is one of the language’s bad parts.

In my practice, I completely avoid use of new.

关于javascript - 如果 Crockford 建议我们将它用于原型(prototype)继承,为什么他说不要使用 new 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202889/

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