在Javascript中使用new和不使用它一样吗?
考虑这段代码:
function klass( z ) {
this.a = z;
return this;
}
var b = klass( 5 );
var c = new klass( 9 );
当我在 Chrome 中运行它并在控制台中检查时,b
结果是 DOMWindow
类型,而 c
是输入klass
。
尽管两者都具有属性 a,但实际上两者都是 klass 的实例。
- 使用new和不使用new一样吗?
- 在这个例子中是一样的,但在其他情况下是不同的吗?
- 效率或行为是否存在差异?
Consider this code:
function klass( z ) {
this.a = z;
return this;
}
var b = klass( 5 );
var c = new klass( 9 );
When I run it in Chrome and check in the console, b
turns out to be of type DOMWindow
, while c
is of type klass
.
Although both have the property a, effectively both being an instance of klass.
- Is using or not using new, the same?
- Is it the same on this example but different in other situations?
- Are there differences in efficiency or behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当像这样调用函数时,
this
将被设置为全局对象,或者,如果您处于严格模式,则undefined
结果,第一个示例(没有
new
) 将返回附加了新a
属性的全局对象。在严格模式下,它会抛出错误,因为this
将被设置为undefined
,并且您无法将a
属性添加到未定义。
当您使用
new
调用函数时,this
值将设置为一个新对象,并从该函数隐式返回 — 无需说return this
为了完整起见,当您将函数作为对象的方法调用时:
this
将被设置为 this 中的对象 -foo
案件。当您使用 apply(或 call)调用函数时,
this
会设置为您指定的任何内容 -foo
再次编辑
我提到了
strict我的回答中的模式
。如果页面位于最顶部,则使用严格模式。
When a function is invoked like this
this
will be set to the global object, or, if you're in strict mode,undefined
As a result, the first example (without the
new
) will return the global object with a newa
property attached. In strict mode it will throw an error sincethis
will be set toundefined
, and you can't add ana
property toundefined
.When you invoke a function with
new
the
this
value is set to a new object, and is implicitly returned from the function—there's no need to sayreturn this
For completeness, when you invoke a function as a method on an object:
this
will be set to the object—foo
in this case.And when you invoke a function with apply (or call)
this
is set to whatever you specify—foo
againEDIT
I mentioned
strict mode
in my answer. A page uses strict mode if it hasat the very top of it.
如果没有
new
,您的函数将仅对this
绑定到的任何内容进行操作,在您的情况下是 DOMWindow。没有创建新实例,而是在 window 对象上设置a
属性。调用该方法两次会破坏之前的结果。试试这个:
Without the
new
your function will just operate on whateverthis
was bound to, in your case the DOMWindow. No new instance is created, thea
property gets set on the window object. Calling the method twice clobbers the previous result.Try this:
这绝对不一样:
如果你不调用
new
,你就不会得到任何新的东西。It's absolutely not the same:
If you don't call
new
, you're not getting anything new.