MyClass.prototype = new Object()和MyClass.prototype = Object之间的区别 [英] Difference between MyClass.prototype = new Object() and MyClass.prototype = Object

查看:115
本文介绍了MyClass.prototype = new Object()和MyClass.prototype = Object之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我,在Javascript中的区别

could anyone please tell me, where in Javascript the difference between

MyClass.prototype = new Object(); //or ... = {}

MyClass.prototype = Object;

是?如果结果没有差异,哪一个是最佳实践方式?

is? And if there is no difference in the result, which one is the best-practise-way-to-go?

推荐答案

你的前两个例子是完全等价的:

Your first two examples are completely equivalent:

MyClass.prototype = new Object(); // empty object
MyClass.prototype = {}; // empty object

您的第三个示例无效,因为您要分配给 MyClass.prototype 对象的引用构造函数,它是一个函数,而不是一个新对象。

Your third example is not valid, since you are assigning to the MyClass.prototype a reference to the Object constructor, and it's a function, not a new object.

我个人更喜欢第二个,对象 literal 初始化程序语法:

I personally prefer the second, the object literal or initialiser syntax:

MyClass.prototype = {prop1: 'value', prop2: 'value2'};
//...
MyClass.prototype.foo = 'bar';
MyClass.prototype.method1: function () {/**/};

编辑:为了回应您的评论,空对象文字 {} 基本上相当于 new Object()因为:

In response to your comment, an empty object literal { } essentially equivalent to new Object() because of this:

生产ObjectLiteral:{}是
评估如下:

The production ObjectLiteral : { } is evaluated as follows:


  1. 创建一个新对象好像通过表达式new Object()。

  2. 返回结果(1)。


有关详细信息,请查看 ECMAScript语言规范(pdf)。

For more details check the 11.1.5 section (Object Initialiser) of the ECMAScript Language Spec (pdf).

编辑:第三个例子赢了'产生任何错误,但一点也不好,例如,如果你之后扩展MyClass.prototype,你可以很容易地破坏Object构造函数:

The third example won't produce any errors, but is not good at all, for example you can easily clobber the Object constructor function if you extend afterward the MyClass.prototype:

MyClass.prototype = Object;
MyClass.prototype.foo = 'bar';

Object.foo === MyClass.prototype.foo; // true

这篇关于MyClass.prototype = new Object()和MyClass.prototype = Object之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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