Reputation: 36028
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?
Upvotes: -1
Views: 268
Reputation: 14746
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.
Upvotes: 0
Reputation: 816404
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
.
Upvotes: 5