Code:
1)
function Person(name,age){
this.name=name;
this.age=age;
}
var p=new Person('stack',100);
console.dir(p);
console.info(p.name);//'stack'.
But I wonder why I can create a new person use:
var p2=new Person(); //no error
There is not a constructor like:
function Person(){}
why?
2)
function Person(name,age){
var _name,_age;
this._name=name;
this._age=age;
}
var p=new Person('stack',100);
console.dir(p);
What’s the difference between this and the 1)’s manner?
If you don’t pass parameters to a function, they will be
undefinedinside the function. You can pass any number of parameters to a function, you just need the name.The only difference in the second version is that you define two local variables which you don’t use and that you name the properties differently. Note that
var _nameis not the same asthis._name.