Huibin Zhang
Huibin Zhang

Reputation: 1110

Why don't need to specify variable in the constructor?

I am learning javascript, in the constructor there isn't a var declaration there, just get and set method there. Could anyone tell me why? I think there should be a statement like var name; in the constructor?

<script>
function Person(name){
    this.getName=function(){
        return name;
    };

    this.setName=function(value){
        name=value;
    };
}
</script>

why don't put

var name

in the constructor?

Upvotes: 0

Views: 35

Answers (3)

Georgi Naumov
Georgi Naumov

Reputation: 4201

setName method is implemented in case you want to change the name of an existing object. e.g:

function Person(name){
    this.getName=function(){
        return name;
    };

    this.setName=function(value){
        name=value;
    };
}

var tom = new Person("tom");
var harry = new Person("harry");

So If you want tom to have new name you must call

tom.setName("Dick");

After this

tom.getName();

Will return "Dick".

Best regards.

Upvotes: 0

mpm
mpm

Reputation: 20155

function Person(name){
    this.getName=function(){
        return name;
    };

    this.setName=function(value){
        name=value;
    };
}

because name is already scoped to Person function since it's an argument of Person

you dont need (and shouldnt) write var name.

Upvotes: 1

Aprillion
Aprillion

Reputation: 22304

because function arguments are already in scope and you don't want to override the argument by undefined?

see What is the scope of variables in JavaScript? to learn more about scope

Upvotes: 1

Related Questions