1. 程式人生 > 其它 >JavaScript之new與不new的區別

JavaScript之new與不new的區別

new 和不 new的區別:

  • 如果 new 了函式內的 this 會指向當前這個 person 並且就算函式內部不 return 也會返回一個物件。
  • 如果不 new 的話函式內的 this 指向的是 window。
function person(firstname,lastname,age,eyecolor)
{
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
    return [this.firstname,this.lastname,this
.age,this.eyecolor,this] } var myFather=new person("John","Doe",50,"blue"); var myMother=person("Sally","Rally",48,"green"); console.log(myFather) console.log(typeof myFather) console.log(myMother) console.log(typeof myMother)
function person(firstname,lastname,age,eyecolor)
{
    this.firstname=firstname;
    
this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; // return [this.firstname,this.lastname,this.age,this.eyecolor,this] } var myFather=new person("John","Doe",50,"blue"); var myMother=person("Sally","Rally",48,"green"); console.log(myFather) console.log(typeof myFather) console.log(myMother) console.log(
typeof myMother)