[英]Creating an object using a constructor with and without `new`
I have noticed I can create the same object using a constructor in two different ways. 我注意到我可以使用构造函数以两种不同的方式创建相同的对象。
var myObj = Object()
var myObj = new Object()
I can add properties to both using these methods. 我可以使用这些方法向两者添加属性。 myObj.age = 1
and myObj['age'] = 1
. myObj.age = 1
和myObj['age'] = 1
。 The properties of both can be accesed the same way. 两者的属性可以相同的方式访问。
So what is the actual difference between these two ways I created myObj
? 那么我创建myObj
这两种方式之间的实际区别是什么? Also is one of these the better way to create an object? 这些方法也是创建对象的更好方法之一吗?
The difference is that the first one simply calls Object()
as a function, within the scope of the window
object. 不同之处在于,第一个函数只是在window
对象的范围内将Object()
作为函数调用。
The second one actually instantiates a new object. 第二个实际上实例化了一个新对象。 It's the one you want to use to create an object. 这是您要用来创建对象的对象。
The difference may not be obvious with the Object()
function, but let's say you create your own type, like so: 与Object()
函数的区别可能并不明显,但是让我们说您创建自己的类型,如下所示:
function User(name) {
this.name = name;
}
var u1 = User("John");
var u2 = new User("Jane");
console.log(u1); // *undefined* because `User()` doesn't return anything.
console.log(this.name); // John
console.log(window.name); // John
console.log(u2.name); // "Jane"
The Object
function itself is a special case--it does create a new Object. Object
函数本身是一个特例-它确实创建了一个新的Object。 But since most functions don't work that way, it's good to get in the habit of using the new
keyword when instantiating things. 但是由于大多数功能都无法正常工作,因此最好在实例化时养成使用new
关键字的习惯。 If you're just creating a plain old Object
, on the other hand, most people prefer the more concise syntax: 另一方面,如果您只是创建一个普通的旧Object
,那么大多数人都喜欢更简洁的语法:
var myObj = {};
The first statement is a function call, meaning that myObj
will get whatever is returned in the Object()
function. 第一条语句是函数调用,这意味着myObj
将获得Object()
函数中返回的任何内容。 As it happens, the function Object()
will provide you with a reference to an Object
object, whereas 'normal' constructors will not. 碰巧的是,函数Object()
将为您提供对Object
对象的引用,而“普通”构造函数则不会。
See fe the following: 请参阅以下内容:
function O(){
this.bla= "bla";
return this;
}
Calling O()
here will yield a reference to window
, not to an instance of O
. 在这里调用O()
将产生对window
的引用,而不是O
的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.