Piero
Piero

Reputation: 79

custom setter method does not work (javascript)

I'm trying to define a method inside the constructor to modify the 'name' attribute (but it doesn't seem to work).I can't figure out what's wrong with my code(I'm newbie). Thanks in advance.

function Animal(){
  this.name=""
  this.setName=function(name){
    this.name=name
  }
}
var myDog=new Animal()
myDog.setName="Max"
console.log(myDog.name)//" "
console.log(myDog.setName)//"Max"

Upvotes: 0

Views: 62

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18965

setName is function so change your code to myDog.setName("Max")

function Animal(){
  this.name=""
  this.setName=function(name){
    this.name=name
  }
}
var myDog=new Animal()
myDog.setName("Max")
console.log(myDog.name)
//console.log(myDog.setName)//"Max"

Upvotes: 1

Related Questions