-1

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

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

so do you mean that function Person(name,age){this.name=name// not equal with _name=name}? whatis the difference?
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
So,It is not nessssary to decare the property _name,just use this._name=name,then the instance of Person will have this property?
@hguser: Yes. This is the only way to declare it. Otherwise (with var) you just create a local variable like in a normal function.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.