Sometimes I am supposed to call new Foo()
to create a new foo object, but sometimes I can just call Foo()
to create it.
In general, for a given function, how do I know which to use?
答案 0 :(得分:1)
new
keyword do?See this question.
new
keyword?If the target function has a .prototype.
and it doesn't return anything (or it returns this
), then you should use new
to get an object with that proto. (Although some people recommend using Object.create(...)
as a clearer alternative.)
or, if the target function assigns things to this.foo
, and you don't think it is trying to set things on the global object, then you should call it with new
.
new
keyword?If you are calling a factory function to create a new object, then you do not need to use the new
keyword.
A factory function will usually create the new object itself, and then return it. It will create the object using { ... }
or Object.create(...)
or by calling another function, or even by using new
itself.
new
keyword?If you just call Foo()
then the body of the Foo function will run with this
pointing to the global object (or in strict mode, with this === undefined
). If the function assigns this.foo
then these will end up modifying the global. Is that what you wanted?
答案 1 :(得分:1)
Considering the following class :
Person = function (name) {
this.name = name;
};
Person.prototype.getName = function () {
return this.name;
};
Using new
to instanciate this class :
john = new Person("John");
john.getName(); // "John"
Is roughly equivalent to the following :
john = {
name: "John",
__proto__: Person.prototype
};
john.getName(); // "John"
As you can see, new
is nothing more than a syntactic sugar, it takes care of binding the prototype of the class to the instance, you don't have to do it yourself.
More about new
: https://stackoverflow.com/a/44733777/1636522.