Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript构造函数序言的目的是什么?_Javascript_Node.js_Design Patterns_Constructor - Fatal编程技术网

javascript构造函数序言的目的是什么?

javascript构造函数序言的目的是什么?,javascript,node.js,design-patterns,constructor,Javascript,Node.js,Design Patterns,Constructor,我经常在许多node.js/javascript源代码中遇到以下构造函数序言 function MyClass () { // prologue if (!(this instanceof MyClass)) { return new MyClass(); } // do actual constructor logic } 你能解释一下这是干什么用的吗?谢谢。instanceof检查对象是否可能是通过给定的构造函数构造的。这个序言是用来处理有人

我经常在许多node.js/javascript源代码中遇到以下构造函数序言

function MyClass () {
    // prologue
    if (!(this instanceof MyClass)) {
        return new MyClass();
    }
    // do actual constructor logic
}

你能解释一下这是干什么用的吗?谢谢。

instanceof
检查对象是否可能是通过给定的构造函数构造的。这个序言是用来处理有人在不使用
new
的情况下调用
MyClass
构造函数的情况。这意味着您可以按照预期的方式使用
MyClass

var c = new MyClass();
…或不带新的

var c = MyClass();
在后一种情况下,在对
MyClass
的调用中,
this
将不是MyClass
实例(它将是
未定义的
[在严格模式下]或全局对象[在松散模式下]),因此作者知道调用方没有使用
new
,只需让函数通过执行返回新的MyClass()来为他们执行
new
而不是它的正常构造工作

有些人喜欢这样做,因此
new
是可选的,另一些人认为这样做是个坏主意。在严格模式之前糟糕的旧日子里,另一种方法是检测调用方未能使用
new
并引发异常:

// Old pre-strict code
if (!(this instanceof MyClass)) {
    throw "MyClass is a constructor, use new";
}
如果不这样做,并且使用松散模式,并将属性指定给
,则将属性指定给全局对象(即全局变量),这是一个坏主意(tm)

但现在我们有了严格的模式,这是使用它的众多原因之一:

"use strict"; // At the top of the file or `script` block

function MyClass() {
    // No need for the check anymore
    this.someProperty = someValue;
}
由于
this.someProperty=someValueMyClass
而没有
new
(因为
将是
未定义的
),code>行将抛出。(调用方是否使用严格模式并不重要;在定义
MyClass
构造函数的代码中使用严格模式就足够了。)


当然,有些人仍然喜欢将
new
设置为可选,在这种情况下,他们仍然需要开场白。

为了避免直接调用构造函数将一些变量注册到全局变量,这是JavaScript的一个著名缺陷

function Foo() {
    // don't do prologue
    this.foo = 'foo';
}

Foo(); // direct call a constructor

console.log(window.foo) // foo, global is polluted.

亲爱的布鲁图斯,读这篇文章吧,错不在我们的明星身上,而在我们自己身上……评论。替换('rutus','rendan');开玩笑吧,我是明星的粉丝。