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?
2 Answers 2
If you don't pass parameters to a function, they will be undefined inside 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 _name is not the same as this._name.
4 Comments
var _name creates a local variable. It will not be accessible from outside the function. this._name creates a property on the object you create with new Person(). See an example: jsfiddle.net/cWtJN var) you just create a local variable like in a normal function.1) it's not mandatory to respect equals number of parameters a function can receive in Javascript. In that case (p2) they will be undefined.
2) you're declaring 2 'private' (just local) variables with var _name,_age; .. there's no need if you're not using them inside that scope.