2013-07-21 31 views
7
var foo = function() { 
    return new moo(); 
} 

var moo = function() { 
    return this; 
} 

如果我执行语句请问new是否返回指定的函数构造函数实例?

new foo() 

我真正能拿到哞的实例?这似乎同时显而易见并且不直观。在功能上,这是应该发生的事情,但同时,如果你不知道内部结构,这是不可预料的。

编辑:我意识到这似乎不直观b.c.在Java构造函数中不能返回任何东西。

这与jquery使用的构造函数模式非常相似。

回答

3

是的,你会得到哞的一个实例。

非直观性是因为事实上,你可以返回比对象本身以外的东西在javascvipt constructor.This是可能的,因为所有的功能都在JS事实上对象。在像java和c#这样的语言中,这是不可能的,构造函数总是返回构造函数所属的对象。您也可以在这些语言中不能调用没有新关键字的构造函数。 无法从构造函数返回任何东西是相同的变薄在JS的东西return this;(假设它使用的构造函数)也增添了些许混乱。

+0

其由于不使用这个关键字! – user2580076

2

你是正确的,你会得到哞

原因的实例为这个如此暧昧是因为只要使用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

当执行代码的新富(...),下面的事情发生:

  1. 创建一个新的对象,从foo.prototype继承。
  2. 使用指定的参数调用构造函数foo,并将其绑定到新创建的对象。新的foo是 等同于新的foo(),即如果没有指定参数列表,则foo是 ,不带参数调用。
  3. 构造函数返回的对象成为整个新表达式的结果。如果构造函数不显式返回对象,则使用步骤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问题:

  1. 构造函数的默认行为是返回“这'如果没有其他东西返回
  2. 如果另一个目的是从构造新创建的对象绑定到“这个”被丢弃返回

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 
} 
+0

@stack_temp是否'this'回答你的问题? – user2580076

+0

[链接](http://jsfiddle.net/xQVuX/)'新创建的对象的构造并不直到执行“这个”的关键字是used'是不正确的。函数本身就是构造函数,如果它没有执行,新的moo也不会被执行。 – Desu