是“新的”仍然不推荐JavaScript? [英] Is "new" still not recommended in JavaScript?

查看:73
本文介绍了是“新的”仍然不推荐JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我看到很多JavaScript代码在制作构造函数时使用new。阅读部分JavaScript的好零件之后,似乎使用新不是猫的睡衣。那是4年前的事了......是不是仍然不推荐?现行标准是什么?

So I see plenty of JavaScript code out there that uses "new" when making constructors. After reading part of JavaScript the Good Parts it seems that using "new" isn't the cat's pajamas. That was 4 years ago though... Is it still not recommended? What is the current standard?

推荐答案

因为何时不推荐? D. Crockford有一个有效的观点和强烈的观点,但是 new 是该语言的一部分,并且它在很多项目中被广泛使用。 new 是原型继承模型的一部分,必须用于使用构造函数创建新实例。 Crockford指出了一个纯函数方法,使用这个上下文,返回这个,以便能够继承属性和方法儿童物品。这是针对常见问题的不同解决方案,但并不意味着不应使用 new 。事实上,有史以来最复制/粘贴的JS片段之一是Crockford的, object.create polyfill,它使用 new

Since when is new not recommended? D. Crockford has a valid point and a strong opinion but new is part of the language and it's very much being used in many projects. new is part of the prototype inheritance model, and must be used to create new instances with a constructor function. Crockford points out a purely functional approach using the this context appropriately and return this to be able to inherit properties and methods between children objects. It's a different solution to a common problem, but it doesn't mean that new shouldn't be used. In fact, one of the most copy/pasted JS snippets of all times is Crockford's, the object.create polyfill, and it uses new:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
} 

这篇关于是“新的”仍然不推荐JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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