简体   繁体   English

内置Javascript中的构造函数

[英]Built in Constructor functions in Javascript

When I do: 当我做:

var person = new Object();  
person.name = "alex";
console.log(person)

output is: 输出是:

Object { name="alex"}

However, say I drop the "new" word and do: 但是,我说放弃“新”字并做:

var person = Object();  
person.name = "alex";
console.log(person)

Output is also: 输出还是:

Object { name="alex"}

Why? 为什么?

Because some built-in functions are just defined to act this way. 因为一些内置函数只是定义为以这种方式运行。 For example see ES5 15.2.1.1 for Object : 例如,参见ES5 15.2.1.1 for Object

15.2.1.1 Object ( [ value ] ) 15.2.1.1对象([值])

When the Object function is called with no arguments or with one argument value , the following steps are taken: 如果在没有参数或具有一个参数的情况下调用Object函数,则执行以下步骤:

  1. If value is null , undefined or not supplied, create and return a new Object object exactly as if the standard built-in Object constructor had been called with the same arguments ( 15.2.2.1 ). 如果valuenullundefined或not provided,则创建并返回一个新的Object对象,就像使用相同的参数调用标准的内置Object构造函数一样( 15.2.2.1 )。
  2. Return ToObject(value) . 返回ToObject(value)

They test whether they have been called with new or not and if not act like they'd have been called with new . 他们测试他们是否被new调用,如果不是他们被称为new调用。

Not all constructors work like this. 并非所有构造函数都像这样工作。 For example Date will return a string when called without new . 例如, Date在没有new情况下调用时将返回一个字符串。


You can implement this yourself: 您可以自己实现:

function Foo() {
    if(!(this instanceof Foo)) {
        return new Foo();
    }
    // do other init stuff
}

Foo() and new Foo() will act the same way (it gets more tricky with variable arguments though). Foo()new Foo()将以相同的方式行事(尽管变量参数变得更加棘手)。

Since your example is an Object type of built-in function, as it is answered above it is the same for this type, it does not work the same way for most of the other built-in functions such as Number(). 由于您的示例是内置函数的Object类型,因为上面的答案对于此类型是相同的,因此对于大多数其他内置函数(例如Number()),它的工作方式不同。 You should be very careful when invoking them with the 'new' keyword or not. 使用'new'关键字调用它们时应该非常小心。 Because by default the 'new' keyword with a function constructor returns an object, not a primitive type directly. 因为默认情况下,带有函数构造函数的'new'关键字返回一个对象,而不是直接返回一个基本类型。 So you can not, for example, check strict equality on two variables that one of them is declared and assigned using new Number() , and the other is with Number() 因此,您不能,例如,检查两个变量的严格相等,其中一个变量是使用new Number()声明和分配的,另一个是使用Number()

An example would be: 一个例子是:

var num1 = Number(26); 
var num2 = new Number(26);

num1 == num2; // returns true

num1 === num2; // returns false

You may checkout the difference at the console log: 您可以在控制台日志中查看差异:

console.log(num1);
> 26

console.log(num2);
> Number {26}
>     __proto__: Number
>     [[PrimitiveValue]]: 26

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM