es5文法下,javascript如何判斷函數是new還是()調用

來源:互聯網
上載者:User

標籤:==   支援   判斷   就會   複製粘貼   cti   ons   粘貼   this   

es5文法沒有支援類class,但是可以通關函數來申明一個類,如下:

function Person(name){

  this.name=name;

}

var john=new Person(‘john‘);

console.log(john.name);//john

但是這個類可以直接像函數執行那樣調用:Person()

判斷是不是被new還是()調用得這樣修改上面這個類:

function Person(name){

  this.name=name;

  if(this instanceof Person){

    alert(‘new調用‘);
  }else{
    alert(‘函數調用‘);
  }

}

new Person(‘xiaoqiang‘)//=> new調用

Person(‘xiaoqiang‘)//=>函數調用

還以用寫法可以方便複製粘貼到任何類裡面如下:

寫法1:

function Person(name){

  this.name=name;

  if(this instanceof arguments.callee){

    alert(‘new調用‘);
  }else{
    alert(‘函數調用‘);
  }

}

new Person(‘xiaoqiang‘)//=> new調用

Person(‘xiaoqiang‘)//=>函數調用

寫法2:

function Person(name){

  this.name=name;

  if(this.constructor === arguments.callee){

    alert(‘new調用‘);
  }else{
    alert(‘函數調用‘);
  }

}

new Person(‘xiaoqiang‘)//=> new調用

Person(‘xiaoqiang‘)//=>函數調用

 

看似上面三種寫法都很完美,但是如何如下調用你就會蒙蔽

 

var jack=new Person(‘jack‘); //=>new 調用

jack.f=Person

jack.f(‘不信你試試‘) //=> new 調用

 

es5文法下,javascript如何判斷函數是new還是()調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.