你是正确的,你会得到哞
原因的实例为这个如此暧昧是因为只要使用new关键字,the newly created object's constructor is not executed until 'this' keyword is used
。新对象绑定到'this'关键字。
指这从:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
当执行代码的新富(...),下面的事情发生:
- 创建一个新的对象,从foo.prototype继承。
- 使用指定的参数调用构造函数foo,并将其绑定到新创建的对象。新的foo是 等同于新的foo(),即如果没有指定参数列表,则foo是 ,不带参数调用。
- 构造函数返回的对象成为整个新表达式的结果。如果构造函数不显式返回对象,则使用步骤1中创建的对象代替 。 (通常构造函数不返回值,但可以 选择这样做,如果他们想覆盖正常的对象创建 过程。)
在你的榜样,也是一个新的对象被创建,但'this'关键字没有被使用,因此foo的构造函数没有被调用,因此函数最终返回moo对象。
http://jsfiddle.net/v5aGu/
var foo = function() {
return new moo();
}
var moo = function() {
return this;
}
var myFoo = new foo(2);
if(myFoo instanceof moo){
alert("moo");
}
if(myFoo instanceof foo){
alert("foo");
}
编辑:解答@Desu提出
id = 0;
var foo = function(){
}
if(new foo() instanceof foo){
alert("yes"); //alerts yes
}
的JavaScript构造101问题:
- 构造函数的默认行为是返回“这'如果没有其他东西返回
- 如果另一个目的是从构造新创建的对象绑定到“这个”被丢弃返回
http://jsfiddle.net/xQVuX/1/
id = 0;
var foo = function(){
}
if(new foo() instanceof foo){
alert("foo yes"); //alerts foo yes because foo returns this as a default behavior
}
var foo2 = function(){
var i=new foo();
return i;
}
if(new foo2() instanceof foo2){
alert("foo2 yes");// does not alert because foo2 returns another object and the newly created object is discarded
}
var foo3 = function(){
this.i = 10;
}
if(new foo3() instanceof foo3){
alert("foo3 yes"); // alerts foo3 yes because foo3 returns this as a default behavior
}
其由于不使用这个关键字! – user2580076