[使用this
关键字调用构造函数时,Java语言中的return语句可以返回new
以外的值的确切情况是什么?
实施例:
function Foo () {
return something;
}
var foo = new Foo ();
[如果我没记错的话,如果something
是非函数原语,则将返回this
。否则返回something
。这是正确的吗?
IOW,something
可以取什么值导致(new Foo () instanceof Foo) === false
?
[[Construct]]
内部属性描述了确切的条件,new
运算符使用该内部属性:
从ECMA-262第3版。版本规格:
new
13.2.2[
[[Construct]]
对象的[[Construct]]
属性为Function
为调用,将执行以下步骤:
- 创建一个新的本地ECMAScript对象。
- 将
F
的[[Class]]
属性设置为[[Class]]
。- 获取
Result(1)
的原型属性的值。- 如果
"Object"
是对象,请将F
的Result(3)
属性设置为[[Prototype]]
。- 如果
[[Prototype]]
不是对象,则将Result(1)
的Result(3)
属性设置为原始Result(3)
原型对象,如下所示:在[[Prototype]]
中进行了说明。- 调用
[[Prototype]]
的Result(1)
属性,并提供Object
作为15.2.3.1值,然后提供传递给[[Call]]
的参数列表作为参数值。- 如果
[[Call]]
为F
,然后返回Result(1)
。- 返回
this
。
请看步骤7和8,只有当[[Construct]]
的类型(Type(Result(6))
构造函数返回的值函数)是not一个对象。
具体示例Type
Object
我找不到关于此事的任何文档,但我认为您是正确的。例如,您可以从构造函数中返回Result(6)
,但不能返回原义的Result(1)
(将被忽略,而是返回Result(6)
)。
试图用简单的话来说明几点。
在javascript中,当您在函数上使用F
关键字时,以及,如果],>
/*
ECMA 262 v 5
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
"4.3.2
primitive value
member of one of the types Undefined, Null, Boolean, Number, Symbol, or String as defined in clause 6"
*/
var Person = function(x){
return x;
};
console.log(Person.constructor);
console.log(Person.prototype.constructor);
console.log(typeof(Person));
console.log(typeof(Person.prototype));
function log(x){
console.log(x instanceof Person);
console.log(typeof x);
console.log(typeof x.prototype);
}
log(new Person(undefined));
log(new Person(null));
log(new Person(true));
log(new Person(2));
log(new Person(""));
//returns a function not an object
log(new Person(function(){}));
//implementation?
//log(new Person(Symbol('%')));
变量将保存返回的复杂对象
new Number(5)
5
注意,返回值或this
只是等式的一部分。
当您使用function Two() { return new Number(2); }
var two = new Two;
two + 2; // 4
two.valueOf = function() { return 3; }
two + 2; // 5
two.valueOf = function() { return '2'; }
two + 2; // '22'
关键字时,将创建一个对象。然后调用该函数以初始化对象。