2012-06-29 136 views
2

我有这样的代码:JavaScript是对象或函数

var obj = function (i) { 
    this.a = i; 
    this.init = function() { 
     var _this = this; 
     setTimeout(function() { 
      alert(_this.a + ' :: ' + typeof _this); 
     }, 0); 
    }; 
    this.init(); 
}; 

obj('1'); 
obj('2'); 
obj('3'); 
new obj('4');​​​ 

http://jsfiddle.net/kbWJd/

脚本警报 '3 ::对象' 三次, '4 ::对象' 一次。

我知道这是为什么。这是因为new obj('4')用它自己的内存空间创建了一个新实例,并且之前的调用共享了它们的内存空间。在obj的代码中,如何确定我是新对象还是函数,因为typeof _this只是说'对象'?

谢谢。

回答

2

这是你在找什么?如果在函数内部执行没有new关键字this的函数等于包含对象(在这种情况下为window)。

if(this === window){ 
    console.log('not an object instance'); 
} else { 
    console.log('object instance'); 
} 

实施例具有不同的包含对象:

var obj = { 

    method: function(){ 

     if(this === obj){ 
      alert('function was not used to create an object instance'); 
     } else { 
      alert('function was used to create an object instance'); 
     } 

    } 

}; 


obj.method(); // this === obj 

new obj.method(); // this === newly created object instance 
+0

YES。谢谢,正是我需要的。 –

+0

这个方法不是要求你知道函数的内部调用什么上下文吗? –

+0

@sam不知道我明白。 if语句确定上下文。 –

2

instanceof操作者可以利用另一种解决方案:

var foo = function() { 
    if (this instanceof foo) { 
     // new operator has been used (most likely) 
    } else { 
     // ... 
    } 
};