JavaScript - object behavior of the main function

As far as I understand, in JavaScript (Gecko variant) this is:

var a = new A();

is syntactic sugar for something like this:

var a = {};
a.__proto__ = A.prototype;
A.call(a);

Because of this, A () (which is equivalent to A.call () ?) And the new A () should produce two different results, for example:

>>> new Date()
Fri Nov 19 2010 01:44:22 GMT+0100 (CET) {}
>>> typeof new Date()
"object"

>>> Date()
"Fri Nov 19 2010 01:44:42 GMT+0100 (CET)"
>>> typeof Date()
"string"

So far so good.

But the main object Functionbehaves differently:

>>> Function('return 123;')
anonymous()
>>> typeof Function('return 123;')
"function"
>>> Function('return 123;')()
123
>>> new Function('return 123;')
anonymous()
>>> typeof new Function('return 123;')
"function"
>>> new Function('return 123;')()
123

Did I miss some trivial thing here?

+5
source share
6 answers

JavaScript . , ( new), ( ) .

- ?

. Function new, ECMAScript 15.3.1:

Function , , new Function. , Function(...) new Function(...) .

Date, , ( EC.9.9.2 ECMAScript) :

Date , , , (UTC).

. Date(...) new Date (...) .

, new. - - , - , , , JavaScript Netscape. Netscape Function(), new. , .

, , . JavaScript . , - , , - . , , .

+3

Function, , , new, .

& sect; 15.3.1: ,

...

function Function (...) new Function (...) .

, , , , :

Array(1,2,3);     // [1,2,3]
new Array(1,2,3); // [1,2,3]

, , (Boolean, String, Number Date), -.

, new, , :

typeof Number("20"); // "number"
typeof String(0xFF); // "string"
typeof String({toString: function () { return 'foo' }}); // "string"
typeof Boolean(""); // "boolean"
typeof Boolean(0); // "boolean"

new, -:

typeof new Number(20); // "object"
typeof new String('foo'); // "object"
typeof new Boolean(true); // "object"

, [[PrimitiveValue]], ( ).

, Date, , .

Date , , , (UTC) ".

+2

, new - new, this instanceof MyClass; new, this === window ( , - gnarf, Namespace.MyClass(), this == Namespace).

( , ), if (this instanceof MyClass) return new MyClass(); ( , ); new .

, , - JavaScript "" ?. .

+1

"" ctor JavaScript, - (, Date) ( , , Date:-). , - ECMA 262, . .

, , ctor, "Function" ( FF):

function X() {
  // but this has issues with nesting in some cases
  if (!(this instanceof X)) {
    return new X()
  } else {
    this.y = 2
  }
}
X().y // => 2

, ECMA... / . - . ECMA 262 .

+1

, Function() , new Function() , .

0

, . , , , , -.

typeof Number(5) == "number"
typeof new Number(5) == "object"

typeof Boolean(0) == "boolean"
typeof new Boolean(0) == "object"

, .

I wrote a blog about creating designers that work with or without the new operator http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html I do not use it, but this is interesting material. This will give you an idea of ​​how you can change the behavior of a function based on whether it is called new or not.

Even after this conversation, I'm still not sure what your question is ...

0
source

All Articles