在Javascript中使用new是否与不使用它相同?

Pet*_*uza 6 javascript class object new-operator

考虑以下代码:

function klass( z ) {
    this.a = z;
    return this;
}

var b = klass( 5 );
var c = new klass( 9 );
Run Code Online (Sandbox Code Playgroud)

当我在Chrome中运行它并检查控制台时,b结果是类型DOMWindow,而c类型klass.

虽然两者都具有属性,既有效地作为一个实例克拉斯.

  • 使用或不使用新的,相同的?
  • 这个例子是否相同但在其他情况下有所不同?
  • 效率或行为是否存在差异?

Ada*_*kis 6

当像这样调用一个函数时

klass(6);  //called function invocation
Run Code Online (Sandbox Code Playgroud)

this 将被设置为全局对象,或者,如果您处于严格模式, undefined

因此,第一个示例(没有new)将返回a附加了新属性的全局对象.在严格模式下,它将抛出一个错误,因为this将被设置为undefined,并且您无法添加a属性undefined.

用函数调用函数时 new

new klass( 9 );  //called constructor invocation
Run Code Online (Sandbox Code Playgroud)

this值设置为一个新对象,并从函数中隐式返回 - 没有必要说return this

为了完整性,当您在对象上调用函数作为方法时:

foo.method();  //called method invocation
Run Code Online (Sandbox Code Playgroud)

this将被设置为对象 - foo在这种情况下.

并且当您使用apply(或call)调用函数时

method.apply(foo)  //called apply invocation 
Run Code Online (Sandbox Code Playgroud)

this被设置为您指定的任何内容 - foo再次

编辑

strict mode在答案中提到过.页面使用严格模式(如果有)

"use strict"
Run Code Online (Sandbox Code Playgroud)

在它的最顶端.


Thi*_*ilo 6

如果没有new你的函数,你将只运行任何this绑定的东西,在你的情况下是DOMWindow.没有创建新实例,该a属性在窗口对象上设置.调用该方法两次破坏了之前的结果.

试试这个:

var b = klass(5)
log.info(b.a)
log.info(b == window)  // b is actually the window object
log.info(window.a)   // also 5

var c = klass(6)
log.info(b.a)     // now set to 6
log.info(c == b)  // c and b are the same
Run Code Online (Sandbox Code Playgroud)