如何判断一个方法是new调用还是一般调用


在看The.Art.and.Science.of.JavaScript 的时候,看到了这个问题,就是在javascript中如何判断一个方法是new调用还是一般调用,在书中给出的代码是

  Javascript代码

function Element(){ 
  if(this==window || 'Element' in this){ 
   console.log("normal"); 
}else{ 
   console.log("new"); 
} 
 
}

  可是这个代码不能解决两个问题:

  1比如加上下面的代码:

  Javascript代码
 Element.prototype.Element=1; 

  这时如果调用new Element()时,由于Element 已经存在于this里面,因此会打印出normal;

  这个很好解决。我是这样写的:

  Javascript代码

function Element(){ 
if(this.__proto__==Element.prototype) 
{console.log("new");}else{console.log("normal");}}

  可是这时又有了第二个问题。

  比如下面的代码:

  Javascript代码

var test= new Element(); 
 
test.temp=Element; 
 
test.temp(); 

  这时的调用,也应该是normal的调用,可是依然打印出new.

  实在想不出来怎么解决第二种情况,因此发出来看那位能够解决这个问题


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3